Python Forum
What this code will output and why?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What this code will output and why?
#1
Today I meet this exercise:

What this code will output and why?

x = [[]]*3
x[0].append('a')
x[1].append('b')
x[2].append('c')
x[0]=['d']

print(x)

I expected to see 'd b c', but whet i run this program i was surprised. The output is [['d'], ['a', 'b', 'c'], ['a', 'b', 'c']].
Why is this code works this way?
Reply
#2
Brcause you are using a 2 dimensional list. Play around with it for a bit and I'm sure you will understand! :)

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(a[0])
print(a[0][1])
Try this code and experiment with it by printing, removing, appending etc
Reply
#3
Output:
[['d'], ['a', 'b', 'c'], ['a', 'b', 'c']]
Reply
#4
x = [[]]*3 this copy 3 list to  same memory adress.
>>> x = [[]]*3
>>> [id(i) for i in x]
[57560800, 57560800, 57560800]
Do it like this.
>>> x = [[] for i in range(3)]
>>> [id(i) for i in x]
[66352912, 66412416, 65766344]
Then it look like this.
x = [[] for i in range(3)]
x[0].append('a')
x[1].append('b')
x[2].append('c')
x[0] = ['d']

print(x)
Output:
[['d'], ['b'], ['c']]
Reply
#5
Thank you for detailed answer. I will experiment with this python feature.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  No desired output for code. James349 1 932 May-19-2023, 05:43 PM
Last Post: deanhystad
  Wrong output on my code. JTNA 2 7,852 Apr-04-2019, 01:55 PM
Last Post: JTNA
  Code to use output from arduino as input (help) Updownrightleft 0 2,205 Nov-03-2018, 11:04 PM
Last Post: Updownrightleft
  adding to code but still getting same output Crackity 7 4,503 Jul-12-2017, 02:36 PM
Last Post: buran

Forum Jump:

User Panel Messages

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