Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I update a list slice but not a string slice in python?

Just curious more than anything why python will allow me to update a slice of a list but not a string?

>>> s = "abc"
>>> s[1:2]
'b'
>>> s[1:3]
'bc'
>>> s[1:3] = "aa"

>>> l = [1,2,3]
>>> l[1:3]
[2, 3]
>>> l[1:3] = [9,0]
>>> l
[1, 9, 0]

Is there a good reason for this? (I am sure there is.)

like image 285
Chris Avatar asked Nov 19 '10 14:11

Chris


People also ask

Can we slice strings in Python?

Python string supports slicing to create substring. Note that Python string is immutable, slicing creates a new substring from the source string and original string remains unchanged.

Does slicing create a new string?

When you slice strings, they return a new instance of String. Strings are immutable objects.

What is slicing in Python explain list and string with slicing?

Slicing StringsSpecify the start index and the end index, separated by a colon, to return a part of the string.

What is :: In slicing?

Consider a python list, In-order to access a range of elements in a list, you need to slice a list. One way to do this is to use the simple slicing operator i.e. colon(:) With this operator, one can specify where to start the slicing, where to end, and specify the step.


1 Answers

Because in python, strings are immutable.

like image 109
Justin Ethier Avatar answered Oct 14 '22 06:10

Justin Ethier