[BangPypers] List of n but same objects

Rajiv Subramanian M rajiv.m1991 at gmail.com
Thu Dec 11 11:28:01 CET 2014


Hello Group,

I am Rajiv, Python/Django developer in a startup, Bangalore. Today when I
experimenting with python I came across the following

CASE 1:

>>> x = range(10)

>>> [iter(x)] * 3

[<listiterator object at 0x7f6aa5594850>,

<listiterator object at 0x7f6aa5594850>,

<listiterator object at 0x7f6aa5594850>]


Thing to Note:

Here all the 3 listiterator object in the list is actually a same single
instance residing at the memory location "0x7f6aa5594850"


CASE 2:

 >>> [iter(x), iter(x), iter(x)]

[<listiterator object at 0x7f6aa5594890>,

<listiterator object at 0x7f6aa55948d0>,

<listiterator object at 0x7f6aa5594910>]


Thing to Note:
In this case literally I created called the iter(x) for 3 times so it
created 3 different listiterator object.

CASE 3:
>>> x = [1, 2, 3]
>>> y = [x] * 3
>>> y
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> y[0][0] = 5
>>> y
[[5, 2, 3], [5, 2, 3], [5, 2, 3]]
>>> x
[5, 2, 3]

Things to Note:
As like in first case, here the list objects inside the list y are not the
duplicates of x but the x itself


Question:
1. How in the first case i.e   [iter(x)] * 3  creates a list of 3 but the
same objects?
2. Is there any other possibility or way (like * operator does here) by
which we can obtain the same result as in CASE 1?
3. Does only list and listiterators objects can behave this way? what other
python datatypes can behave this way?

~ Regards
Rajiv M


More information about the BangPypers mailing list