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 do I map a list of values to specified colors? larkypython 4 161 Nov-05-2019, 09:22 AM
Last Post: larkypython
  Getting Unique values from LISTS aankrose 2 172 Oct-17-2019, 05:33 PM
Last Post: aankrose
  list of lists iterate only sends the last value batchenr 1 159 Sep-24-2019, 07:04 AM
Last Post: Gribouillis
  addition for elements in lists of list ridgerunnersjw 3 185 Sep-15-2019, 07:11 AM
Last Post: perfringo
  creating a list from lists of lists ridgerunnersjw 1 296 Sep-13-2019, 05:22 PM
Last Post: snippsat
  How to create a list with all values being zero 357mag 4 257 Jul-14-2019, 03:43 PM
Last Post: ThomasL
  Remove \n from list of values within a pandas columns klllmmm 2 462 Jun-24-2019, 05:16 AM
Last Post: klllmmm
  Store a python list of lists in a database to use for searches later on klllmmm 3 483 Jun-20-2019, 07:54 AM
Last Post: buran
  update values in list based on dictionary bunti 3 822 Jun-10-2019, 07:26 AM
Last Post: perfringo
  flattening a list with some elements being lists Skaperen 17 1,406 Apr-09-2019, 07:08 AM
Last Post: perfringo

Forum Jump:

Users browsing this thread: 1 Guest(s)