Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 918
Victor Polevoy Avatar asked Apr 16 '26 00:04

Victor Polevoy


1 Answers

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
like image 96
Ashwini Chaudhary Avatar answered Apr 18 '26 13:04

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!