Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python do slice-by-reference on strings?

Tags:

python

string

I want to know if when I do something like

a = "This could be a very large string..." b = a[:10] 

a new string is created or a view/iterator is returned

like image 922
GuidoMB Avatar asked Apr 19 '11 20:04

GuidoMB


People also ask

Is slicing possible in string 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.

Can Slicing be used for strings?

Slicing StringsYou can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string.

Which operator is used for slicing a string in python?

The slice operator [n:m] returns the part of the string starting with the character at index n and go up to but not including the character at index m.

How does python slicing work?

Python slice() FunctionThe slice() function returns a slice object. A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.


1 Answers

Python does slice-by-copy, meaning every time you slice (except for very trivial slices, such as a[:]), it copies all of the data into a new string object.

According to one of the developers, this choice was made because

The [slice-by-reference] approach is more complicated, harder to implement and may lead to unexpected behavior.

For example:

 a = "a long string with 500,000 chars ..." b = a[0] del a 

With the slice-as-copy design the string a is immediately freed. The slice-as-reference design would keep the 500kB string in memory although you are only interested in the first character.

Apparently, if you absolutely need a view into a string, you can use a memoryview object.

like image 73
BlueRaja - Danny Pflughoeft Avatar answered Sep 30 '22 20:09

BlueRaja - Danny Pflughoeft