Skip to content Skip to sidebar Skip to footer

Python3 Zip Result Used Twice

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) : f

Solution 1:

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).

Post a Comment for "Python3 Zip Result Used Twice"