Reputation: 71
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?
Upvotes: 1
Views: 306
Reputation: 18457
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)]
Upvotes: 5