VP.
VP.

Reputation: 16705

python multiple 'for' statement in one row

I wanna do some refactoring of my code, in perl I remember was some statement like (a, b, c) = (x, y, z) it called like 'multiple assigning'. I also heard this thing exists in python, but I need not exactly 'multiple assigning'.

I have 3 lists with same size, and I need to know - can I get items from them by something like this:

for a, b, c in a_list, b_list, c_list:
   pass

For my tests it just gets first 3 elements of a_list (a = a_list[0], b = a_list[1], c = a_list[2]) but I need to get one element from a_list (a = a_list[0]), one element fro b_list (b = b_list[0]) and same from c_list and to get next items on each iteration.

Upvotes: 3

Views: 484

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

Use zip:

for a, b, c in zip(a_list, b_list, c_list):
   pass

Your code didn't work because it is actually equivalent to:

for lis in (a_list, b_list, c_list):
    a, b, c = lis  #assign the items of list fetched from the `tuple` to a, b ,c

Upvotes: 5

Simeon Visser
Simeon Visser

Reputation: 122336

You can do:

for a, b, c in zip(a_list, b_list, c_list):
   pass

If the lists of not of equal length you can use itertools.izip_longest which will use a "fill value" when one list is longer than the other.

Upvotes: 5

Related Questions