+ 1

What is the output of the following code?

v=[1,2,3] r=[ 'g', v[:], 'a' ] v[1]=0 print(r)

21st Dec 2017, 3:09 AM
Drishti Sharma
Drishti Sharma - avatar
11 Answers
+ 9
you could've tested it yourself on code playground...
21st Dec 2017, 5:24 AM
Ahri Fox
Ahri Fox - avatar
+ 8
@drishti r != [ 'g' , [1,0,3], 'a' ] because python code are executed top to down by interpreting the code line by line so in first instruction it assign an array v=[1,2,3] then it interprate and execute the 2 instruction which is r=['g', v[:] ,' a'] by which output come as [ 'g' , [1,2,3], 'a' ] and then it execute 3rd instruction v[1]=0 by which the value of the 2 element of array v become 0 then it execute 4 instruction print (r) which prim the value of r which is [ 'g' , [1,2,3], 'a' ] and if you now print(v) it will print v[1,0,3]
21st Dec 2017, 3:58 AM
GAWEN STEASY
GAWEN STEASY - avatar
+ 7
If you switch lines 2 and 3 you do get [ 'g' , [1,0,3], 'a' ].
21st Dec 2017, 4:10 AM
David Ashton
David Ashton - avatar
+ 7
@Gawen print(v) will print v[1,0,3] of course thats just a typo. You have such a funny profile. I would like to call you a: Code Gamer. No offence of course, you made me asked myself, why i don't like to be challenged...while you seem to love it....i m still confusedšŸ˜‚šŸ˜ šŸ˜ØšŸ˜„.....šŸ˜‰
21st Dec 2017, 4:27 AM
Arnoud Loschnig
Arnoud Loschnig - avatar
+ 5
welcome @drishti don't worry you will understand the behavior of python language very soon because it is really nice language šŸ˜ŠšŸ˜Š
21st Dec 2017, 4:03 AM
GAWEN STEASY
GAWEN STEASY - avatar
+ 4
['g', [1,2,3,], 'a'] Look it please ā†‘ā†‘ā†‘ :)
21st Dec 2017, 3:23 AM
James16
James16 - avatar
+ 1
I am not getting why v[1] doesn't get updated while printing r
21st Dec 2017, 3:10 AM
Drishti Sharma
Drishti Sharma - avatar
+ 1
yesss ... thanks @David :)
21st Dec 2017, 4:18 AM
Drishti Sharma
Drishti Sharma - avatar
0
please can you explain me why r != [ 'g' , [1,0,3], 'a' ]
21st Dec 2017, 3:27 AM
Drishti Sharma
Drishti Sharma - avatar
0
Oh.. thanks @Gawen . Python is my first programming language so my basics are not that great as of now. thank you so much :)
21st Dec 2017, 4:02 AM
Drishti Sharma
Drishti Sharma - avatar
0
yes, I am loving the process.. :)
21st Dec 2017, 4:04 AM
Drishti Sharma
Drishti Sharma - avatar