Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing two or more list in a single for-loop

provided that I have two lists in same length, list_a, list_b.

I can print they items in a single for loop as follows:

for i in range(0, len(list_a)):
    print "%s %s" % (list_a[i], list_b[i])

is there any alternative and elegant way to do above mentioned task ?

I have tried

for a, b in list_a, list_b:
    print ""
like image 976
prgbenz Avatar asked Dec 10 '25 10:12

prgbenz


1 Answers

You need zip():

for a, b in zip(list_a, list_b):
     # whatever

When the lists are long and you are using Python 2.x, you might prefer itertools.izip() to save some memory.

like image 139
Sven Marnach Avatar answered Dec 11 '25 23:12

Sven Marnach



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!