Python Forum
Unexpected behavior accessing list elements.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unexpected behavior accessing list elements.
#1
Not homework but I'm a noob ;)

Quote:a = [[0,0,0],[0,0,0],[0,0,0]]
b = [[0] * 3] * 3

print(a == b)

print(' a =', a)
print(' b =', b)

a[0][0] = 1
b[0][0] = 1

print('a after =', a)
print('b after =', b)

Outputs:
Quote:True
a = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
b = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
a after = [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
b after = [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

I can't understand why 'b after' isn't the same as 'a after'.

Cheers.
Reply
#2
Your assignment statement for b is creating three references to the same list, where a is three distinct lists. Consequently, b[0], b[1], and b[2] are all pointing to the same list object.

a = [[0,0,0],[0,0,0],[0,0,0]]
b = [[0] * 3] * 3

print(a[0] is a[1])
print(b[0] is b[1])
Output:
False True
And yes, it's a little confusing. Wink
tonyflute and BashBedlam like this post
Reply
#3
Thanks, everything is fine now after the explanation. It would have taken me a while to work that one out!! Cheers
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  help with adding duplicates elements together in a list 2ECC3O 5 1,970 Sep-10-2022, 07:11 AM
Last Post: 2ECC3O
  How to find difference between elements in a list? Using beginner Basics only. Anklebiter 8 4,254 Nov-19-2020, 07:43 PM
Last Post: Anklebiter
  Get 5 most unique combinations of elements in a 2D list wanttolearn 1 2,280 Sep-24-2020, 02:26 PM
Last Post: buran
  Loop through elements of list and include as value in the dictionary Rupini 3 2,586 Jun-13-2020, 05:43 AM
Last Post: buran
  How can I print the number of unique elements in a list? AnOddGirl 5 3,194 Mar-24-2020, 05:47 AM
Last Post: AnOddGirl
  Unexpected change to a list in a small amount of self-contained code Johno 5 2,789 Mar-15-2020, 05:06 PM
Last Post: jefsummers
  Extracting elements in a list to form a message using for loop Tony04 2 2,324 Oct-25-2019, 05:55 PM
Last Post: ichabod801
  Sum of elements on the list recursive sev 3 2,513 Jun-20-2019, 02:14 PM
Last Post: sev
  reach the elements in the list ptah 7 4,963 Oct-04-2017, 08:12 PM
Last Post: ptah
  Newbie to Python - Problem in accessing Dictionaries and List sambill 1 3,030 Aug-17-2017, 07:38 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

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