86

I am trying to import the izip module like so:

from itertools import izip

However after recently changing over from Python 2.7 to 3 - it doesn't seem to work.

I am trying to write to a csv file:

writer.writerows(izip(variable1,2))

But I have no luck. Still encounter an error.

3 Answers 3

97

In Python 3 the built-in zip does the same job as itertools.izip in 2.X(returns an iterator instead of a list). The zip implementation is almost completely copy-pasted from the old izip, just with a few names changed and pickle support added.

Here is a benchmark between zip in Python 2 and 3 and izip in Python 2:

Python 2.7:

from timeit import timeit

print(timeit('list(izip(xrange(100), xrange(100)))',
             'from itertools import izip',
             number=500000))

print(timeit('zip(xrange(100), xrange(100))', number=500000))

Output:

1.9288790226
1.2828938961

Python 3:

from timeit import timeit

print(timeit('list(zip(range(100), range(100)))', number=500000))

Output:

1.7653984297066927

In this case since zip's arguments must support iteration you can not use 2 as its argument. So if you want to write 2 variable as a CSV row you can put them in a tuple or list:

writer.writerows((variable1,2))

Also from itertools you can import zip_longest as a more flexible function which you can use it on iterators with different size.

1
  • aargh - apparently I do not understand edit grace periods as well as I thought I did. now the edit logs are confusing Commented May 8, 2018 at 18:32
24

One of the ways which helped me is:

try:
    from itertools import izip as zip
except ImportError: # will be 3.x series
    pass
18

Use zip instead of izip directly in python 3, no need to import anything.

For further visit here.

3
  • 1
    For further what? :)
    – bers
    Commented Dec 20, 2019 at 9:40
  • 1
    For further understanding and looking at the patch where it was fixed. Maybe a good way to go. @bers Commented Dec 20, 2019 at 10:38
  • according to Raymond Hettinger izip is much faster and way efficient Commented May 24, 2023 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.