By A.Wan


2013-07-17 14:45:02 8 Comments

I'm sure this has been answered somewhere but I wasn't sure how to describe it.

Let's say I want to create a list containing 3 empty lists, like so:

lst = [[], [], []]

I thought I was being all clever by doing this:

lst = [[]] * 3

But I discovered, after debugging some weird behavior, that this caused an append update to one sublist, say lst[0].append(3), to update the entire list, making it [[3], [3], [3]] rather than [[3], [], []].

However, if I initialize the list with

lst = [[] for i in range(3)]

then doing lst[1].append(5)gives the expected [[], [5], []]

My question is why does this happen? It is interesting to note that if I do

lst = [[]]*3
lst[0] = [5]
lst[0].append(3)

then the 'linkage' of cell 0 is broken and I get [[5,3],[],[]], but lst[1].append(0) still causes [[5,3],[0],[0].

My best guess is that using multiplication in the form [[]]*x causes Python to store a reference to a single cell...?

Related Questions

Sponsored Content

5 Answered Questions

[SOLVED] Catch multiple exceptions in one line (except block)

17 Answered Questions

[SOLVED] Selecting multiple columns in a pandas dataframe

19 Answered Questions

[SOLVED] Generate random integers between 0 and 9

  • 2010-10-22 12:48:29
  • aneuryzm
  • 1893566 View
  • 1331 Score
  • 19 Answer
  • Tags:   python random integer

13 Answered Questions

[SOLVED] List of lists changes reflected across sublists unexpectedly

15 Answered Questions

[SOLVED] How does Python's super() work with multiple inheritance?

28 Answered Questions

[SOLVED] Random string generation with upper case letters and digits

  • 2010-02-13 12:23:58
  • Hellnar
  • 872155 View
  • 1333 Score
  • 28 Answer
  • Tags:   python string random

26 Answered Questions

[SOLVED] How do I clone a generic list in C#?

2 Answered Questions

[SOLVED] Storing the result of Minhash

Sponsored Content