+ 2

Outputs(don't know if it's has been asked before..)

I had a doubt... Consider this snippet.. L1=[10,5,7] 1. L2=L1 L1[0]=3 print (L1) print (L2) 2. L2=L1[:] L1[0]=3 print (L1) print (L2) Can somebody justify the output?? 1. [3,5,7] [3,5,7] 2. [3,5,7] [10,5,7] Why is it like this?? both of them get the entire content of L1 in L2 right??

31st Jul 2018, 12:11 PM
Ultra Yam ZGH
Ultra Yam ZGH - avatar
4 Antworten
+ 2
The first example has L2 as a reference to L1, so they are actually the exact same object. The second example has L2 as the slice of the entire list L1, so while it appears the same, it's not the same list, as slicing makes a new list.
31st Jul 2018, 12:18 PM
LunarCoffee
LunarCoffee - avatar
+ 3
“ok so whenever we equate variables they're always referring to the same object??” - actually no. Variables are an example of what’s called an ‘immutable’ object. So if you do the following: a=1 b=a b=2 print(a) this returns 1. Equating variables and changing one variable doesn’t change the other. In your example you used a list, which is, unlike variables, ‘mutable’. So equating two lists and changing one DOES change the other. Immutable objects include variables and tuples. Mutable objects include lists, sets and dictionaries. Hope that makes sense.
31st Jul 2018, 1:22 PM
Russ
Russ - avatar
+ 3
Thnx for the pro tip!
1st Aug 2018, 5:46 AM
Ultra Yam ZGH
Ultra Yam ZGH - avatar
+ 2
ok so whenever we equate variables they're always referring to the same object??(And thnx for clarification)
31st Jul 2018, 12:20 PM
Ultra Yam ZGH
Ultra Yam ZGH - avatar