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, 3445, 234, 34]
for i, b in myList:
print ("first= %d, second= %d" % (i, b))
4 Answers 4
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.
1 Comment
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 in range(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.
1 Comment
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:
for i, j in l:
print i, 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)
1 Comment
You can iterate over multiple sequential values at once by combining iter and zip, like so:
values = [ 1, 2, 3, 4, 5, 6 ]
valueIterator = iter( values )
for xCoord, yCoord in zip( valueIterator, valueIterator ):
print( xCoord, yCoord )
Which would output:
1 2
3 4
5 6
This will work in both Python 2 and 3, and can be scaled to iterate over any number of values at a time by adding more iterator arguments to zip.
For example: for x, y, z in zip( valueIter, valueIter, valueIter ):.
Or if you need even more without an unreasonably long line:
iterReference = iter( self.values )
iterRefs = [ iterReference ] * 10 # Multiple references to the same iterator
for v1, v2, v3, v4, v5, v6, v7, v8, v9, v10 in zip( *iterRefs )
Besides being more readable, it's also several times more efficient than the range + splicing solution:
range + splicing: 4.5734569989144804e-05
iter + zip: 1.8035800009965896e-05
(timeit with 10000 iterations and a list of 600 values.)
Note that this exhausts the iterator, so if you reference it again, it'll essentially be empty. In which case you can just refer back to the original list if needed.
(i,b)