what does 'a=b=c=[]' do

Chris Kaynor ckaynor at zindagigames.com
Wed Dec 21 18:12:53 EST 2011


On Wed, Dec 21, 2011 at 2:25 PM, Eric <einazaki668 at yahoo.com> wrote:
>
> Is it true that if I want to create an array or arbitrary size such
> as:
>   for a in range(n):
>      x.append(<some function...>)
>
> I must do this instead?
>   x=[]
>   for a in range(n):
>      x.append(<some function...>)

You can also use a list comprehension:

x = [<some function...> for a in range(n)]

Or extend and a generator expression:

x = []

x.extend(<some function...> for a in range(n))

Or map and a generator function:

map(x.append, (<some function...> for a in range(n)))


I would recommend either your way, the first of, or the second of my ways,
depending on the full context.

>
>
> Now to my actual question.  I need to do the above for multiple arrays
> (all the same, arbitrary size).  So I do this:
>   x=y=z=[]

This creates a new object, then assigns the labels x, y, and z to that
object.

>   for a in range(n):
>      x.append(<some function...>)
>      y.append(<some other function...>)
>      z.append(<yet another function...>)

Then this appends the items to each of those labels, which, as they
pointing to the same object, appends to all of the labels. The "variables"
in Python are merely labels, and assigning to different labels does not
automatically copy the object.

Consider:
a = []
b = a
a.append(1)
print b

[1]


>
> Except it seems that I didn't create three different arrays, I created
> one array that goes by three different names (i.e. x[], y[] and z[]
> all reference the same pile of numbers, no idea which pile).
>
> This surprises me, can someone tell me why it shouldn't?  I figure if
> I want to create and initialize three scalars the just do "a=b=c=7",
> for example, so why not extend it to arrays.  Also, is there a more
> pythonic way to do "x=[], y=[], z=[]"?

The above rules apply in all cases, however are generally invisible on
immutable objects (strings, ints, floats, tuples). In the case of a=b=c=7,
you will find that all of a, b, and c point to the same object (try the
"id" function or "is" operator). Doing the operation a += 1 after a=7 will
create a new int* with the value 7+1 and assign it to the label a.

* In CPython, there exists an optimization where small ints are cached,
namely from -7 to 255 (the lower bound I stated may be wrong). This
improved performance in most cases, but is CPython specific - other
implementations such as PyPy or IronPython may behave differently.

>
> It's a slick language but I still have trouble wrapping my brain
> around some of the concepts.
>
> TIA,
> eric
> --
> http://mail.python.org/mailman/listinfo/python-list
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20111221/079dd587/attachment-0001.html>


More information about the Python-list mailing list