Search code examples
pythonpython-3.xzip

Python - Use two zipped lists multiple times


I have the following zip: a = zip(list_a, list_b). It was always my understanding that once I zipped a, it would stay zipped. Such that the following would work:

for iteration in range(100):
   for i, j in a:
      # do something

But I noticed that on the second iteration a was empty. First of all, is my understanding of zip correct, and secondly, is there a simple single line alternative that would fit in this situation?


Solution

  • zip returns an iterator; it produces each pair once, then it's done. So the solution is usually to just inline the zip in the loop so it's recreated each time:

    for iteration in range(100):
       for i, j in zip(list_a, list_b):
          # do something
    

    or if that doesn't work for some reason, just list-ify the zip iterator up front so it's reusable:

    a = list(zip(list_a, list_b))
    

    and then use your original looping code.