-1

(I am a beginner)

Here is a code using concept of list and the question is asking to print out the following result:

[1, 'A', 3,] [1, 'A', 3,]

as shown in the below screenshot:

enter image description here

Given that the option being chosen is a correct one.

**What bother me is that why the code in that option works...

especially the code "a[1 ] = a[1 ][0]"

**

I searched in the internet but I have not found a concrete description about it.

Can anyone provide some help? Thank you very much!

  • Useful reading: https://nedbatchelder.com/text/names.html – jonrsharpe Apr 21 '17 at 09:53
  • they are not the same! What I want to know is the chosen code works. I don't know why "a[1] = a[1][0]" works actually – wongwong3000 Apr 21 '17 at 11:10
  • Then please [edit] to clarify what you still don't understand. – jonrsharpe Apr 21 '17 at 11:11
  • I have edited. Please see the bold sentence in my post! – wongwong3000 Apr 21 '17 at 11:16
  • Why wouldn't it? What precise part of it don't you understand? Have you tried running it in a debugger or on e.g. http://pythontutor.com/ or just adding a `print` between the two lines? – jonrsharpe Apr 21 '17 at 11:35
  • I have edited the post again. The code I don't know is "a[1] = a[1][0]". I have tried and checked all your suggestions but I still don't know why. I spent about an hour on only this line of code but I still couldn't figure out the principle behind... – wongwong3000 Apr 21 '17 at 11:42

1 Answers1

0

Because lists are mutable objects in python. You are creating list by declaring

 a = [1,2,3]

and then declaring that b = a, at which point both a and b point to the same list. (note that this does not work with immutable types, such as integers in python).

Christian W.
  • 2,532
  • 1
  • 19
  • 31
  • Maybe my original question is not that clear. I have just edited it a bit. Sorry about that. What question is actually, why the following code works? b[1] = ‘AB’ a[1] = a[1][0] – wongwong3000 Apr 21 '17 at 10:44
  • Because a[1] points to the newly created 'AB', which itself can be accessed by indexing, which means that a[1][0] points to 'A'. – Christian W. Apr 23 '17 at 18:30