473,408 Members | 1,821 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

Unexpected behavior of list of list

Hi,

The following code

listoflists = [[]]*2
listoflists[0].append(1)

appends(1) to both listoflists[0] and listoflists[1] (which I did not
expect)

while

listoflists = [[]]*2
listoflists[0] = [1]
listoflists[0].append(2)

works as expected.i.e. only listoflists[0] gets 2 appended to it and
any further operations work as expected.

I can't figure out why. Any help with explaining this would be much
appreciated

thanks!
-Kaushik

Mar 10 '07 #1
4 1477
On Mar 9, 8:30 pm, "kghose" <kaushik.gh...@gmail.comwrote:
Hi,

The following code

listoflists = [[]]*2
listoflists[0].append(1)

appends(1) to both listoflists[0] and listoflists[1] (which I did not
expect)

while

listoflists = [[]]*2
listoflists[0] = [1]
listoflists[0].append(2)

works as expected.i.e. only listoflists[0] gets 2 appended to it and
any further operations work as expected.

I can't figure out why. Any help with explaining this would be much
appreciated

thanks!
-Kaushik
OK, I looked at the previous few threads and I think I understand why.
I refered to this page http://www.python.org/doc/faq/progra...mensional-list

thanks
-kaushik

Mar 10 '07 #2
En Fri, 09 Mar 2007 22:30:09 -0300, kghose <ka***********@gmail.com>
escribió:
The following code

listoflists = [[]]*2
listoflists[0].append(1)

appends(1) to both listoflists[0] and listoflists[1] (which I did not
expect)
See latest posts on this list, or read the FAQ.

--
Gabriel Genellina

Mar 10 '07 #3
On Fri, 09 Mar 2007 17:30:09 -0800, kghose wrote:
Hi,

The following code

listoflists = [[]]*2
listoflists[0].append(1)

appends(1) to both listoflists[0] and listoflists[1] (which I did not
expect)
I think you will find the same question raised barely a few hours ago.

Hint:
>>list_of_lists = [[]]*2
id(list_of_lists[0])
-1211466452
>>id(list_of_lists[1])
-1211466452

Notice that both inner lists have the same ID? That tells you that they
are the same list.

Like about what [obj]*2 does. Does it create multiple copies of obj? No it
does not. Python never makes copies of objects unless you explicitly tell
it to.

[] on it's own creates a new empty list, so [[], []] creates a list with
two DIFFERENT empty lists in it. [[]] creates a list with one empty list
in it; *2 makes a second reference (not a copy!) of that empty list.

while

listoflists = [[]]*2
listoflists[0] = [1]
listoflists[0].append(2)

works as expected.i.e. only listoflists[0] gets 2 appended to it and
any further operations work as expected.
>>list_of_lists[0] = [] # creates a new empty list
id(list_of_lists[0])
-1211466228
>>id(list_of_lists[1]) # same ID as before
-1211466452


You know, now that Python has a warnings module, it would be really good
if list-of-lists*int raised a warning. Does anyone know if that's feasible
or possible? It needn't catch every imaginable Gotcha, just the common
case. I'm thinking something like this:

# pseudo-code
class list:
def __mul__(self, count):
for item in self:
if isinstance(item, list):
warn("this duplicates references, not copies")
break
...do the rest


--
Steven.

Mar 10 '07 #4
En Fri, 09 Mar 2007 23:58:59 -0300, Steven D'Aprano
<st***@REMOVE.THIS.cybersource.com.auescribió:
You know, now that Python has a warnings module, it would be really good
if list-of-lists*int raised a warning. Does anyone know if that's
feasible
or possible? It needn't catch every imaginable Gotcha, just the common
case. I'm thinking something like this:

# pseudo-code
class list:
def __mul__(self, count):
for item in self:
if isinstance(item, list):
warn("this duplicates references, not copies")
break
...do the rest
But isn't the same with almost any other object (except inmutable ones)?
[{}]*5, [set()]*5, even [my_instance]*5?
It's hard to tell when it's a legitimate use and when it's a mistake, and
the checking+warning call has a cost...

--
Gabriel Genellina

Mar 10 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
by: Simon Wittber | last post by:
For the first time, I have been bitten by Python. The below code produces the results: False True when I initially expected the results: False False It took me a while to work out that...
2
by: Attila Feher | last post by:
Hi all, I have not done much work around exceptions; and even when I do I avoid exception specifications. But now I have to teach people about these language facilities, so I am trying them out...
7
by: Dave Hansen | last post by:
OK, first, I don't often have the time to read this group, so apologies if this is a FAQ, though I couldn't find anything at python.org. Second, this isn't my code. I wouldn't do this. But a...
2
by: Indra Heckenbach | last post by:
I have recently come across an unusual behavior with Postgres 7.3.4 on a Linux RH 9 system. My database has encoding set to "UNICODE", and the table includes Japanese text. I'm trying to issue a...
3
by: Kail | last post by:
Hello all, today i found a very strange situation of ArrayList - at least for me. let's take 3 elementes that were put into list variable (list.add(point 1 - 3)): Point(1,1); Point(2,2);...
6
by: Samuel M. Smith | last post by:
I have been playing around with a subclass of dict wrt a recipe for setting dict items using attribute syntax. The dict class has some read only attributes that generate an exception if I try to...
62
by: ashu | last post by:
hi look at this code include <stdio.h> int main(void) { int i,j=2; i=j++ * ++j * j++; printf("%d %d",i,j); return 0;
2
by: Dimitri Furman | last post by:
SQL Server 2000 SP4. Running the script below prints 'Unexpected': ----------------------------- DECLARE @String AS varchar(1) SELECT @String = 'z' IF @String LIKE ''
2
by: mbeachy | last post by:
Some rather unexpected behavior in the set_default/set_defaults methods for OptionParser that I noticed recently: <Option at 0x-483b3414: -r/--restart> {'restart': None} {'retart': False,...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.