Misuse of list comprehensions?

Thomas Bellman bellman at lysator.liu.se
Tue May 20 07:04:58 EDT 2008


"Diez B. Roggisch" <deets at nospam.web.de> writes:

> bearophileHUGS at lycos.com wrote:

>> The Example 2 builds a list, that is then thrown away. It's just a
>> waste of memory (and time).

> No, it doesn't. It uses append because it refers to itself in the
> if-expression. So the append(c) is needed - and thus the assignment
> possible but essentially useless.

Yes it does.  A list comprehension *always* creates a list.  In
this case it will be a list of None, since that is what list.append()
returns.  See this:

    >>> new=[]
    >>> s="This is a foolish use of list comprehensions"
    >>> [ new.append(c) for c in s if c not in new ]
    [None, None, None, None, None, None, None, None, None, None, None,
     None, None, None, None, None, None]

Yes, you do get a correct result in 'new', but you *also* create
a 17 long list with all elements set to None, that is immediately
thrown away.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"I refuse to have a battle of wits with an   !  bellman @ lysator.liu.se
 unarmed person."                            !  Make Love -- Nicht Wahr!



More information about the Python-list mailing list