Python Forum
Why does this list of lists end up with the same values
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why does this list of lists end up with the same values
#1
How can this be explained?
x = [[]]*3
x[0].append('a')
print(x)
>>> returns [['a'], ['a'], ['a']]
Reply
#2
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
[1]
You probably wanted to create 3 distinct lists, e.g.:
x = [[] for _ in range(3)]
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Using Lists as Dictionary Values bfallert 1 11 56 minutes ago
Last Post: menator01
  Copying the order of another list with identical values gohanhango 7 1,134 Nov-29-2023, 09:17 PM
Last Post: Pedroski55
  Search Excel File with a list of values huzzug 4 1,216 Nov-03-2023, 05:35 PM
Last Post: huzzug
  Comparing List values to get indexes Edward_ 7 1,138 Jun-09-2023, 04:57 PM
Last Post: deanhystad
  List all possibilities of a nested-list by flattened lists sparkt 1 915 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Adding values with reduce() function from the list of tuples kinimod 10 2,637 Jan-24-2023, 08:22 AM
Last Post: perfringo
  user input values into list of lists tauros73 3 1,064 Dec-29-2022, 05:54 PM
Last Post: deanhystad
  returning a List of Lists nafshar 3 1,059 Oct-28-2022, 06:28 PM
Last Post: deanhystad
  Creating list of lists, with objects from lists sgrinderud 7 1,612 Oct-01-2022, 07:15 PM
Last Post: Skaperen
  AttributeError: 'list' object has no attribute 'values' ilknurg 4 14,943 Jan-19-2022, 08:33 AM
Last Post: menator01

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020