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
  • 76,296
  • 45
  • 192
  • 242
AmericanMade
  • 393
  • 1
  • 6
  • 19

3 Answers3

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
  • 33,530
  • 5
  • 49
  • 82
  • 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
  • 49,108
  • 7
  • 48
  • 110
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,151
  • 1
  • 15
  • 31
  • 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