Re: Questions about list-creation



i should also mention that

a=[i for i in xrange(10)]

and

b=list(j for j in xrange(10))

isn't really just a difference of using [] vs. list()
the first case is a list comprehension, the second case is a generator
comprehension which is then converted to a list
(the bug only applies to list comprehensions, not generator comprehensions)

i.e. notice that you can do this
''.join(x for x in ['a','b','c'])
no list or [] involved - it's just a generator comprehension being
passed to a function.




On Mon, Nov 30, 2009 at 1:12 PM, inhahe <inhahe@xxxxxxxxx> wrote:
On Mon, Nov 30, 2009 at 12:22 PM, Manuel Graune <manuel.graune@xxxxxxxx> wrote:

Hello,

in (most) python documentation the syntax "list()"
and "[]" is treated as being more or less the same
thing. For example "help([])" and "help(list())" point
to the same documentation. Since there are at least
two cases where this similarity is not the case, (see below)
can someone explain the reasoning behind this and point to
further / relevant documentation?
(To clarify: I am not complaining about this, just asking.)


1.)

when using local variables in list comprehensions, say

a=[i for i in xrange(10)]

the local variable is not destroyed afterwards:

print "a",a
print "i",i

using the similar code

b=list(j for j in xrange(10))

the local variable is destroyed after use:

print "b",b
print "j",j


I could be wrong, but I think this was actually a bug that was fixed later.

and 2)

a=list([])

vs.

b=[[]]


those don't return the same thing
list([]) will create a shallow copy of [], which will of course be []

i can't think of a place where you'd want to use list() instead of [],
but sometimes you might want to use 'list', such as in a defaultdict,
in which case it's being used as a factory


Regards,

Manuel Graune

--
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
--
http://mail.python.org/mailman/listinfo/python-list


.



Relevant Pages

  • Re: list comprehensions
    ... Elaine Jackson wrote: ... > List comprehensions don't work the way you intuitively expect them to work. ... 100 Haskell programmers have been asked ... > documentation to find out about list comprehensions? ...
    (comp.lang.python)
  • list comprehensions
    ... List comprehensions don't work the way you intuitively expect them to work. ... realize many people have no intuitions about how list comprehensions 'should' ... So I guess what I want to ask is: Can somebody explain the semantics of list ... documentation to find out about list comprehensions? ...
    (comp.lang.python)
  • Re: loop scope
    ... > consistency we now have in treatment of all local variables. ... without leaking variables out of list comprehensions ... (or loops). ...
    (comp.lang.python)