Saturday, 7 September 2013

About memory efficiency: range vs xrange, zip vs izip

About memory efficiency: range vs xrange, zip vs izip

I was reading the following topic: Make dictionary from list with python
The initial problem is to transform the tuple (1,'a',2,'b',3,'c') into the
dictionary {1: 'a', 2: 'b', 3: 'c'}. Many interesting solutions were
given, including the following two:
Solution 1
dict(x[i:i+2] for i in range(0, len(x), 2))
Solution 2
dict(zip(*[iter(val_)] * 2))
In solution 1, why bother creating the actual list with range? Wouldn't
xrange( 0, len(x), 2 ) be more memory efficient? Same question for
solution 2: zip creates an actual list. Why not using itertools.izip
instead?

No comments:

Post a Comment