1

I know that you can do nested for loops, for example:

for ch in a:
    for ch2 in ch:
        print(ch2)

However, I've seen for loops that go like this:

for ch, ch2 in a:
    # blah blah

Are these two loops equivalent? Or does the second loop do something different than the first?

1
  • They are not same.The first loop will gives a product of your iterable's items since the second one is just a multi-assignment loop which iterates over iterable a only works if a has duplex items. Commented Aug 14, 2015 at 20:59

1 Answer 1

5

No, they are not.

The second is an example of multiple assignment. If you assign to a tuple, Python unpacks the values of an iterable into the names you gave.

The second loop is rather equivalent to this:

for seq in a:
    ch = seq[0]
    ch2 = seq[1]
    # blah blah

As @Kasramvd points out in a comment to your question, this only works if a is a sequence with the correct number of items. Otherwise, Python will raise a ValueError.


Edit to address dict iteration (as brought up in comment):

When you iterate over a Python dict using the normal for x in y syntax, x is the key relevant to each iteration.

for x in y:   # y is a dict
    y[x]      # this retrieves the value because x has the key

The type of loop you are talking about is achieved as follows:

for key, val in y.items():
    print(key, 'is the key')
    print('y[key] is', val)

This is still the same kind of unpacking as described above, because dict.items gives you a list of tuples corresponding to the dict contents. That is:

d = {'a': 1, 'b': 2}
print(d.items())    # [('a', 1), ('b', 2)]
Sign up to request clarification or add additional context in comments.

7 Comments

So when you do a loop, does ch go forwards from seq[0] onwards while seq[1] moves onwards from [1] ? I'm working with a dictionary here and so I'm a tad confused on the interaction of unpacking; would having two assigned variables here present the key and its value?
@Hackxx Updated my answer to address dict iteration and how the above notion fits into it.
OHHH okay so because dict.items unpacks into a duplex element tuple, the multiple assignment targets the 0th and 1st element right?
@Hackxx Yes, precisely. If you were to iterate like for x in y.items(), x would be a tuple each time, but since you provide two assignment targets, Python realizes and unpacks it for you so you have the individual elements.
I see!! So if you were to (for some unknown reason) use the for x in y.items() loop, you would have to un-tuple everything in the end assuming you want the individual element?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.