+ 1

What does the code do?

>>> a = [1, 2, 3] >>> a[11:11] [] >>> a[11:11] = "xyz" >>> a [1, 2, 3, 'x', 'y', 'z']

14th Jan 2022, 2:58 AM
FanYu
FanYu - avatar
5 Answers
+ 3
š“•š“›š“Ø It's all 'bout the syntax. Slices, when assigned, actually modifies the mutable object from which the slice was made. Using the slice as a value is another matter. See: foo = [1, 2, 3] # 'foo' is modified coz Python was made like that, to modify the list when you're directly making assignments to it foo[:2] = "o" # the slice now makes a separate object in the heap because you aren't assigning to it directly, just coz the syntax is like that print(id(foo), id(foo[:2])) # Basically, slicing and slice assignment are two separate things. It's a feature Python has. Just some crazy syntax :)
15th Jan 2022, 2:55 PM
Œ 慤
Œ 慤 - avatar
+ 7
Since you're doing slice assignment, the source will be treated as a sequence. When a string is used as a sequence, each character is a separate element(character), so it gets split up and inserted into the list. If you want to replace the slice with the whole string, wrap it in a list. >>> a[11:11] = ["xyz"] Hope you know why a[11:11] returns empty list [] https://www.sololearn.com/discuss/2955122/?ref=app
14th Jan 2022, 4:31 AM
Simba
Simba - avatar
+ 5
Hey! I found the actual reason. Since, python doesn't have references, It's all about slice assignment not memory locations. Hope it helps you. https://stackoverflow.com/questions/10623302/how-does-assignment-work-with-list-slices
15th Jan 2022, 10:07 AM
Simba
Simba - avatar
+ 3
Simba Thanks for reply. I don't know how to describe the question. Maybe we can change the code to: >>> a = [1, 2, 3] >>> id(a[1]), id(a[1:1]) (1655224256, 17999848) >>> a[1:1] = "xyz" >>> id(a[1]), id(a[1:1]) (52164608, 17999848) >>> a [1, 'x', 'y', 'z', 2, 3]
14th Jan 2022, 4:52 AM
FanYu
FanYu - avatar
+ 1
Simba Thanks again. Perhaps I'll find the answer myself by reading the source code of CPython. >>> a = [1, 2, 3] >>> id(a[0]), id(a[1]), id(a[2]) (1655224240, 1655224256, 1655224272) >>> id(a[0:0]), id(a[1:1]), id(a[2:2]), id(a[11:11]) (19356136, 19356136, 19356136, 19356136)
14th Jan 2022, 5:25 AM
FanYu
FanYu - avatar