0
t1 = ("a", "b", "c", "d")
t2 = (1, 2, 3, 4)
z = zip(t1, t2)
print(list(z))
print(dict(z))

It seems like we can cast the zip object only once. After z = zip(t1, t2) only the first casting either list(z) or dict(z) works and the other one does not work. Why is it so ?

Akshay J
  • 5,362
  • 13
  • 68
  • 105

1 Answers1

0

Another option is to use the itertools.tee() function to create a second version of your generator:

from itertools import tee
t1 = ("a", "b", "c", "d")
t2 = (1, 2, 3, 4)
z,z_backup = tee(zip(t1, t2))
print(list(z))
print(dict(z_backup))
William Feirie
  • 624
  • 3
  • 7
  • Beware, for simple tuples as sources this is fine, but if `t1` and `t2` are infinite, `tee`ing them will buffer all data consumed by only one of the tees, which could produce exploding memory consumption if you're not careful. In your example, after the next-to-last line executes, the entire `zip`ped data is buffered! – wberry Mar 08 '18 at 01:36
  • Note: If you'll end up running out one of the `tee`d generators to exhaustion before even beginning to iterate the other, you're better off constructing a `list`/`tuple` from the original generator and iterating it an arbitrary number of times. `tee` would have to store the same data as the `list`/`tuple`, but imposes additional overhead; the overhead is only worth it if you're advancing the `tee`-ed generators in parallel (or close to it) where the cache stays small. In this case, just doing `z = tuple(zip(t1, t2))`, then `print(list(z))`, `print(dict(z))` makes more sense. – ShadowRanger Mar 08 '18 at 01:38