Jacques Gaudin
Jacques Gaudin

Reputation: 16958

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 ?

  1. Using zip() twice

    for j in range(123) :
        for x,y in zip(list1,list2) :
            doSomething()
    ....
    for x,y in zip(list1,list2) :
        doSomethingElse()
    
  2. 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

Answers (1)

Martin Konecny
Martin Konecny

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

Related Questions