Many newbie questions regarding python

Hrvoje Niksic hniksic at xemacs.org
Sat Oct 9 06:20:50 EDT 2010


alex23 <wuwei23 at gmail.com> writes:

> If anything, I feel like the list comp version is the correct solution
> because of its reliability, whereas the multiplication form feels like
> either a lucky naive approach or relies on the reader to know the type
> of the initialising value and its mutability.

Other than list comp being slower, I'd like to point out that in some
cases the multiplication is far from being naive.  Consider this
pattern:

def in_groups_of(n, iterable):
    """Yield items of iterable packed in tuples of size n."""
    return itertools.izip(*[iter(iterable)] * n)

>>> for a, b, c in in_groups_of(3, xrange(9)):
...   print a, b, c
... 
0 1 2
3 4 5
6 7 8

In the call to itertools.izip we are actually counting on list
repetition to refer to the same object.  Rewriting it as the list
comprehension would break it:

def in_groups_of(n, iterable):
    return itertools.izip(*[iter(iterable) for _ in xrange(n)])

>>> for a, b, c in in_groups_of(3, xrange(9)):
...   print a, b, c
... 
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8




More information about the Python-list mailing list