Skip to content Skip to sidebar Skip to footer

For Loop With Multiple Iterating Values

I am trying to understand how multiple values in a Python FOR LOOP works. I tried to create my own test, but it doesn't work. Why? Thanks! My test: myList = [4, 5, 7, 23, 45, 65

Solution 1:

Try it with

myList = [(4, 5), (7, 23), (45, 65), (3445, 234)]                      

The general concept is called tuple unpacking. A simpler example:

a, b = (1, 2)

i.e. a for loop is not required.

Solution 2:

You can use slices if you want to iterate through a list by pairs of successive elements:

>>>myList = [4, 5, 7, 23, 45, 65, 3445, 234]>>>for x,y in (myList[i:i+2] for i inrange(0,len(myList),2)):
    print(x,y)

4 5
7 23
45 65
3445 234

You can also do this sort of thing to iterate through strings via substrings of a given size (since slice operators also apply to strings). For example, you can do this in bioinformatics when you want to iterate through the codons of a string representing DNA or RNA.

Solution 3:

What you have defined there is a loop with two iterators.

Python will iterate over the elements of myList and assign this value to i then will pick the first element and check if it can be iterated (e.g. a tuple or another list) and will assign b to this iteratable elemement.

In this case let's say mylist= [(1,1), (2,2)]

Then you can do:

fori, jinl:
   printi, j

and you will get

1 1

2 2

Why? Because, the second one is an iterator and will loop through the internal elements and spit them out to the print function. (so it does another "hidden" for loop)

If you want to get multiple variables from different lists (need to be same length) you do (e.g.)

list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
for i, j in zip(list1, list2);
    print i, j

So the general answer to your question is Iterators + Python magic (meaning that it will do things you haven't asked it to)

Post a Comment for "For Loop With Multiple Iterating Values"