Reputation: 16958
I am using twice the result of zip
on two lists in two distinct for
loops in Python 3. What's the most pythonic way of writing this ?
Using zip() twice
for j in range(123) :
for x,y in zip(list1,list2) :
doSomething()
....
for x,y in zip(list1,list2) :
doSomethingElse()
Storing the result of zip as a list
z=list(zip(list1,list2))
for j in range(123) :
for x,y in z :
doSomething()
for x,y in z :
doSomethingElse()
I would really appreciate to hear about the internals of Python in both cases.
Upvotes: 0
Views: 718
Reputation: 59601
I would use the first method:
for j in range(123) :
for x,y in zip(list1,list2) :
doSomething()
....
for x,y in zip(list1,list2) :
doSomethingElse()
In Python 3, the zip method does not create a new list of pairs from your existing lists. It simply creates an iterator that references the input lists for each iteration. It's very efficient compared to the Python 2 way which created an entirely new list.
For this reason you can use zip
command multiple times, as I believe this makes the code easier to read and more succinct (no instantiation of a new list reference at the top of the code, in general you want to avoid create named references if you can avoid it since it gives you one more reference name you need to remember - this is also part of the reason anonymous functions are more appealing).
Upvotes: 1