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

Python • Why does this work like this

$
0
0
What I have written works as needed. However, it does not operate in the way I expected and I like to understand the mechanisms behind the scenes. Please consider the following code:

Code:

#this routine explores how to slice a ring thats part of# a list of stringskeys=['foist','secund','thoid']linelist = list()linelist.append('this is the foist line')linelist.append('This is the secund line') linelist.append('this is the thoid line')for line in linelist:    for key in keys:        x=line.find(key)        if(x != -1):            line = line[0:x]            print(line)            #linelist.append(line)print('-------------------------------')for line in linelist:    print(line)
When run as presented it yields the following output

Code:

this is the This is the this is the -------------------------------this is the foist lineThis is the secund linethis is the thoid line
When I uncomment line 15 and rerun it results in the following output

Code:

this is the This is the this is the -------------------------------this is the foist lineThis is the secund linethis is the thoid linethis is the This is the this is the 
My understanding is that strings in python are immutable. 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.

What I don't understand is in line 13 I modify the string which should adjust the pointer.

I can then add the modified string to linelist as shown in the bottom of the second block. However, the original;l contents of linelist are unchanged when I go back out to the original namespace outside the for block. How can the members of line[index] be both changed and unchanged? is the for statement making a copy of the contents of linelist[0] and then throwing it away after it goes of of scope?

Statistics: Posted by ras_oscar — Fri Sep 05, 2025 12:01 am



Viewing all articles
Browse latest Browse all 8093

Trending Articles