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
86.9k58 gold badges215 silver badges262 bronze badges
asked May 2, 2016 at 23:38
1
  • 3
    Your list doesn't contain tuples of (i,b) Commented May 2, 2016 at 23:39

4 Answers 4

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.

answered May 2, 2016 at 23:41
Sign up to request clarification or add additional context in comments.

1 Comment

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: stackoverflow.com/questions/10867882/…
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.

answered May 2, 2016 at 23:50

1 Comment

Good to know! Thanks!
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)

answered May 2, 2016 at 23:55

1 Comment

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.
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.

answered Apr 21, 2023 at 21:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.