+ 1

Plz explain how 10 is the output when we have to print the sum of list1

def guess(list1): list2=list1 list2.append(4) list1=[5,6,7] list1 = [1,2,3] guess(list1) print (sum(list1))

27th Jan 2020, 4:59 PM
Navneet
Navneet - avatar
3 Respostas
+ 3
list2 is just another name for list1. Then you give the name list1 to a new list. the original list still exists under another name, and it's the one that is actually changed. 1+2+3+4==10
27th Jan 2020, 5:11 PM
HonFu
HonFu - avatar
+ 2
Santiago Pavoni, this is not the decisive factor. Look at this variation of the code: def guess(list1): list2=list1 list2.append(4) list1=[5,6,7] abc = [1,2,3] guess(abc) print (sum(abc)) If you try this, the effect will still be the same. No, the point is that list2 is just another name for list1, and list1 is just another name for abc. 3 names, but only one list! That's why you can still print it on the outside. list1 = [5, 6, 7] strips the name list1 off the original object and sticks it to a completely new list. So what you do with this list, has no effect on that other list.
28th Jan 2020, 10:10 AM
HonFu
HonFu - avatar
+ 1
I guess it's because list1 is in global scope and list2 is in local scope. Bue i'm not sure
28th Jan 2020, 6:02 AM
Santiago Pavoni