Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Why does this list of lists end up with the same values
How can this be explained?
x = [[]]*3
>>> returns [['a'], ['a'], ['a']]
After you execute x = [[]]*3, x is a list containing 3 references to the same list. Basically, you've given the inner list three names: x[0], x[1] and x[2].
When you modify the list, you can see the change no matter which name you use.

The same would happen if you did this:
>>> a = b = []
>>> a.append(1)
>>> b
You probably wanted to create 3 distinct lists, e.g.:
x = [[] for _ in range(3)]
scidam likes this post
You can read or watch Ned Batchelder's Python Names and Values. This should answer you question in pretty comprehensive way.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  How to put the items of one list in new generated lists Bobbear 1 133 Jun-12-2020, 06:08 AM
Last Post: buran
  access dictionary with keys from another and write values to list redminote4dd 6 228 Jun-03-2020, 05:20 PM
Last Post: DeaD_EyE
  Inserting values from multiple lists sqlite azulu 1 305 May-24-2020, 08:40 AM
Last Post: ibreeden
  Compare Two Lists and Replace Items In a List by Index nagymusic 2 331 May-10-2020, 05:28 AM
Last Post: deanhystad
  Add items from one list to list of lists PUP280 5 588 May-05-2020, 03:47 PM
Last Post: PUP280
  sorting list of lists pframe 5 315 Apr-17-2020, 09:31 PM
Last Post: Larz60+
  Grabbing comma separed values from SQLite and putting them in a list PythonNPC 8 368 Apr-10-2020, 02:39 PM
Last Post: buran
  Can't seem to figure out how to put all of the lists items from a loop into 1 list Cosmosso 4 482 Feb-21-2020, 02:40 PM
Last Post: Cosmosso
  how to compare a list to a list of lists kevthew 1 297 Dec-22-2019, 11:43 AM
Last Post: ibreeden
  Randomly assign values in List 1 to a value in List 2 Seneca260 7 864 Dec-16-2019, 12:57 PM
Last Post: BamBi25

Forum Jump:

Users browsing this thread: 1 Guest(s)