Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

importing izip from itertools module gives NameError in Python 3.x

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.

like image 209
iAmNewToPYTHON Avatar asked Sep 18 '15 19:09

iAmNewToPYTHON


People also ask

What is Izip in Python?

izip() returns an iterator that combines the elements of the passed iterators into tuples. It works similarly to zip() , but returns an iterator instead of a list.

What is itertools in Python 3?

Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.

How itertools works in Python?

The itertools. combinations() function takes two arguments—an iterable inputs and a positive integer n —and produces an iterator over tuples of all combinations of n elements in inputs . >>> list(it. combinations(bills, 3)) [(20, 20, 20), (20, 20, 10), (20, 20, 10), ... ]


2 Answers

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.

like image 170
Mazdak Avatar answered Sep 22 '22 16:09

Mazdak


One of the ways which helped me is:

try:     from itertools import izip as zip except ImportError: # will be 3.x series     pass 
like image 21
Vasyl Lyashkevych Avatar answered Sep 20 '22 16:09

Vasyl Lyashkevych