2

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))
Akavall
  • 82,592
  • 51
  • 207
  • 251
AmericanMade
  • 453
  • 1
  • 9
  • 22

4 Answers4

5

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.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
  • Thanks for info! I just googled tuple unpacking and that explains exactly what I was wondering. This link spells it out even a little more thoroughly if anyone's interested: http://stackoverflow.com/questions/10867882/tuple-unpacking-in-for-loops – AmericanMade May 02 '16 at 23:49
4

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.

John Coleman
  • 51,337
  • 7
  • 54
  • 119
1

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)

MayTheSchwartzBeWithYou
  • 1,181
  • 1
  • 16
  • 32
  • Thanks for the details! I like that you added that little explanation of how the second one is an iterator. That helps me see what's going on. – AmericanMade May 03 '16 at 00:14
0

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.

Durgan
  • 71
  • 5