list comprehension

Simon Forman rogue_pedro at yahoo.com
Mon Jul 3 13:51:50 EDT 2006


cmdrrickhunter at yaho.com wrote:
> I woulkdn't interate at the same time.  zip takes two lists, and makes
> a single list of tuples, not the other way around.  The easilest
> solution is
> feed_list = [ix.url for ix in feeds_list_select]
> feed_id = [ix.id for ix in feeds_list_select]

The zip built-in function takes any number of sequences:

>>> help(zip)
Help on built-in function zip in module __builtin__:

zip(...)
    zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

    Return a list of tuples, where each tuple contains the i-th element
    from each of the argument sequences.  The returned list is
truncated
    in length to the length of the shortest argument sequence.

Iterating over feeds_list_select twice is once too many.  : )


> Also, a big feature of list comprehension is it filters too... for
> example
> high_id_names = [ix.url for ix in feeds_list_select if ix.id > 500]
> Sometimes list comprehensions just read nicely.
> a wrote:
> > hey guys
> > this is gr8
> > but in cheetah
> > i use
> > for test in $ix
> > $test.url
> > end for
> > to iterate thru loop
> >
> > now how do i iterate feed_list and feed_id along with i,
> > thanks a lot

I don't understand what you're asking here, but if you mean that you'd
like the index of 'ix' along with the ix.url and ix.id attributes, then
you can do that like this:

N = [(i, ix.url, ix.id) for i, ix in enumerate(feeds_list_select)]

but then using zip(*N) would give you three tuples: indices, feed_list,
feed_id

you might do something like this:

N = ((i, ix.url, ix.id) for i, ix in enumerate(feeds_list_select))

for index, url, id in N:
    do something with the url, id, and index here

Note that there are ()'s around the "list" comprehension, not []'s,
this makes it a generator rather than a list comprehension.  It works
the same way, but where the list form runs "at once" and creates a
list, the generator form will return the (i, ix.url, ix.id) tuples as
the "for index, url, id" loop iterates through them, thus saving the
overhead of a list construction and additional iteration.

I hope this makes sense and indeed answers something like your
question. ;-)

HTH,
~Simon




More information about the Python-list mailing list