Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 2-D list element assignment
nm = 4
c = [[0, False]] * nm
c[0][0] = 1
I expected that it should give an output as [0, False] (Printed 4 times). Instead, the output is [1, False](Printed 4 times).
Can anyone explain?
[x]*n -- replicates x n-times, i.e. [x]*n = [x, x, ....ntimes, x]
[0, False] is a mutable object (it is a list), so, each time it is replicated, internally, Python uses a pointer to the same object: so a target list -- [x, x, ..., x] is just a set of the same objects.
So, when you change one of them, you change all object(s) at once.

You can avoid this behavior if you define the list as follows:

z = [[0, False], [0, False], [0, False], [0, False]]

In this case, [0, False] items are internally presented as different objects,
so, if you try to change one of them, e.g. z[0][0] = 1, this willn't affect on others.

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Select a part of an element of a list with Index BollerwagenIng 0 236 Aug-09-2019, 09:27 AM
Last Post: BollerwagenIng
  Replace a list or string element with a random one.. pianistseb 3 285 May-09-2019, 08:24 AM
Last Post: buran
  Extract a List element NewBeie 4 374 May-03-2019, 09:49 AM
Last Post: NewBeie
  IndexError: list assignment index out of range Apretext 3 497 Apr-25-2019, 09:29 PM
Last Post: Yoriz
  How to list number of times element is in defaultdict and delete it mrapple2020 3 282 Apr-15-2019, 07:34 AM
Last Post: perfringo
  Unable to locate element no such element gahhon 6 502 Feb-18-2019, 02:09 PM
Last Post: gahhon
  Converting List of 3 Element Tuple to Dictionary fooikonomou 11 986 Jan-14-2019, 09:51 AM
Last Post: perfringo
  Replace element in a nested list nagymusic 4 1,843 Nov-19-2018, 08:03 PM
Last Post: nilamo
  Accessing first list element when at end of loop! JY450 1 422 Aug-14-2018, 12:50 PM
Last Post: perfringo
  Print element of list if string included = element of another list silfer 4 850 Jul-30-2018, 10:29 AM
Last Post: silfer

Forum Jump:

Users browsing this thread: 1 Guest(s)