Can someone please explain why the output of this code is what it is?! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can someone please explain why the output of this code is what it is?!

nums = [1, 2] nums.append(nums) print(nums) print(nums[2]) print(nums[2][2]) print(nums[2][2][2]) print(nums==nums[2])

20th Feb 2017, 2:00 AM
Hamid Ariannejad
Hamid Ariannejad - avatar
2 Answers
+ 3
After the call "nums.append(nums)", nums will become a list with the third item being a reference to a list (in this case a reference to itself). Therefore, nums will look like [1,2,<ref_to_nums>]. When you go to nums[2], you will just get a reference to the nums list. And, every print you listed (except the last comparison), will just print the nums list itsef, because index 2 of the nums list is the nums list. The last print will be True, because, again, nums[2] is just a reference to nums. ... Just remember the third item is just a reference to the list. Hope that's somewhat clear.
20th Feb 2017, 2:12 AM
Jehad Al-Ansari
Jehad Al-Ansari - avatar
+ 2
Complementary: To avoid copying an array by reference and perform "deep" copy, use the slice notation of Python... In the case of the example, the behavior change if you write: nums.append( nums[ : ] ) ... as now, new element inserted in nums is a real copy by value, not just by reference ;)
20th Feb 2017, 8:00 AM
visph
visph - avatar