+ 3

Printing array with reference

Can someone explain me why it is 7? lst1 = [1,2,3,4] lst2 = lst1 lst1 [0] = 7 print(lst2 [0])

26th Dec 2017, 4:30 AM
john arnold barrozo
john arnold barrozo - avatar
4 ответов
+ 10
lst1 = [1,2,3,4] lst2 = lst1 lst1 [0] = 7 print(lst2 [0]) # list1 has a list of elements assigned to it # list2 has assigned list1 so it has same elements as list 1 # list1[0]=7 it assign list1 1st element to 7 # list1 and list2 are same so when we update list1 the elements of list2 is also updated so 7 overwrite in both the list at 1st element # print(list2[0]) it print the 1st elements at list2 which is 7 due to overwrite so finally the output is 7
26th Dec 2017, 6:43 AM
GAWEN STEASY
GAWEN STEASY - avatar
+ 5
I don't know python, but I know few other languages, so I might be wrong, arrays are stored with references , only one copy is shared with all , hence modifying one changes all the copies this concept is common in most of the languages
26th Dec 2017, 4:39 AM
Morpheus
Morpheus - avatar
+ 3
thanks everyone, now I get it 😀
26th Dec 2017, 5:02 AM
john arnold barrozo
john arnold barrozo - avatar
+ 3
7? is not the correct topic to set. Please set your topic properly to get more correct questions from us.
26th Dec 2017, 5:17 AM
Calviղ
Calviղ - avatar