Does modifying a list slice change the whole list.. Or will it just make a copy of it in the memory? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Does modifying a list slice change the whole list.. Or will it just make a copy of it in the memory?

I read somewhere that it make a copy.. And if it does... Why does this happen: a=[1, 2,3,4,5,6,7] a[1:5]=reversed(a[1:5]) print (a) Output: [1, 5,4,3,2,6,7]

29th Apr 2020, 1:16 AM
Y AD Ù
Y AD Ù - avatar
4 Answers
+ 1
Its because, just like strings, you cant change the actual string without altering the original. All it is is aliasing and thats just saying "This variable refers to this other variable" so theyre still technically the same A fix to this Is the .copy() method a = [1,2,3,4,5,6,7] b = a.copy() #The copy isnt 'a', just the same values sooo... b[1:5] = b[4:0:-1] print(a) print(b) Gives output of: [1,2,3,4,5,6,7] [1,5,4,3,2,6,7]
30th Apr 2020, 12:22 AM
Slick
Slick - avatar
+ 1
But Slick ... But why we gave b=a.. And then we modified b.. That means b shld have changed.. But why does a change..?
30th Apr 2020, 12:13 AM
Y AD Ù
Y AD Ù - avatar
+ 1
Ooo i get it now Slick TY
30th Apr 2020, 12:55 AM
Y AD Ù
Y AD Ù - avatar
0
That will change them for good. Even if you use an ailias... a = [1,2,3,4,5,6,7] print(a) b = a b[1:5] = a[4:0:-1] print(a) print(b) Output: [1,2,3,4,5,6,7] #'a' before [1,5,4,3,2,6,7] #'a' after we change 'b' [1,5,4,3,2,6,7] #'b' after we change 'b' The "=" operator is for assigning value, meaning whatever precedes that sign is now equal in value to whats after. In this case, they are also the same list object
29th Apr 2020, 11:07 AM
Slick
Slick - avatar