Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 8621

Python • Re: Why does this work like this

$
0
0
My understanding is that strings in python are immutable.
yes

I believe that means when a string is changed, the string is copied with alterations to a new memory location and the memory value in the pointer is altered to point to the altered string.
Yes. Different address, different value.
The operation line = line[0:3] copies the string (partially). So 'line' references a new memory location and value now. The previous memory location still exists as the list named linelist still exists.

Python has the operator 'is' "Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location"

Code:

linelist = list()linelist.append('ABC')# python is efficient in memory management and 'knows'# which initializer strings are used. Nice feature.line = "ABC"if line is linelist[0]: print("ABC line is linelist[0]")for line in linelist:    if line is linelist[0]: print("line is linelist[0]")     x = line    if x is linelist[0]: print("x is linelist[0]")    if x is line: print("x is line")        # python creates a fresh variable line as value is changed    line = line[0:1]    if line is linelist[0]: print("not expected: modified line is linelist[0]")    if x is line: print("not expected: x is modified line")print ("linelist[0]", linelist[0])

Statistics: Posted by ghp — Fri Sep 05, 2025 8:26 am



Viewing all articles
Browse latest Browse all 8621

Trending Articles