Python Forum
2d Array adds last element to entire list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
2d Array adds last element to entire list
#3
Your initial problem was that you were not making different lists, but just several copies of one list. The construction: [[]] * num takes the inside list and makes num references to it, but they're all the same list. So each time through was overwriting the previous trips through the loop.

>>> players = [[0] * 4] * 3
>>> players
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> players[0][1] = "x"
>>> players
[[0, 'x', 0, 0], [0, 'x', 0, 0], [0, 'x', 0, 0]]
For this to work, you'd need to make different lists.

>>> players = [[0] * 4 for x in range(3)]
>>> players
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> players[0][1] = "x"
>>> players
[[0, 'x', 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Reply


Messages In This Thread
RE: 2d Array adds last element to entire list - by bowlofred - Nov-19-2020, 08:25 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  element in list detection problem jacksfrustration 5 370 Apr-11-2024, 05:44 PM
Last Post: deanhystad
  Elegant way to apply each element of an array to a dataframe? sawtooth500 7 424 Mar-29-2024, 05:51 PM
Last Post: deanhystad
  Make entire script run again every 45 mo NDillard 0 323 Jan-23-2024, 09:40 PM
Last Post: NDillard
  list in dicitonary element problem jacksfrustration 3 708 Oct-14-2023, 03:37 PM
Last Post: deanhystad
  Find (each) element from a list in a file tester_V 3 1,228 Nov-15-2022, 08:40 PM
Last Post: tester_V
  Сheck if an element from a list is in another list that contains a namedtuple elnk 8 1,844 Oct-26-2022, 04:03 PM
Last Post: deanhystad
  functional LEDs in an array or list? // RPi user Doczu 5 1,610 Aug-23-2022, 05:37 PM
Last Post: Yoriz
  Membership test for an element in a list that is a dict value for a particular key? Mark17 2 1,218 Jul-01-2022, 10:52 PM
Last Post: Pedroski55
  How to find the second lowest element in the list? Anonymous 3 2,022 May-31-2022, 01:58 PM
Last Post: Larz60+
  check if element is in a list in a dictionary value ambrozote 4 1,979 May-11-2022, 06:05 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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