2

I'm very new to Python and am having trouble trying to write a replace function. The aim is to display a list, and then display the same list with a character being changed.

The code being used to call the function is:

str_list = ['s', 'h', 'r', 'u', 'g', 'g', 'e', 'd']

print("\nreplace Test")
new_str = list_function.replace(str_list, 'g', 'z')
print(list_function.to_string(str_list))
print(list_function.to_string(new_str))

new_str = list_function.replace(str_list, 'a', 'y')
print(list_function.to_string(new_str))

The code defining the function is:

def replace(my_list, old_value, new_value):
    new_list = my_list
    for k in range(0, length(new_list)):
        if new_list[k] == old_value:
            new_list[k] = new_value
    return my_list

However when I run the program, the output is:

replace Test
s, h, r, u, z, z, e, d
s, h, r, u, z, z, e, d
s, h, r, u, z, z, e, d

I'd like only the second list to be altered, and I ran the debugger and found out that str_list is being altered as well as new_list, but I just cannot work out what I'm doing wrong. Any help would be greatly appreciated.

2 Answers 2

3

when you do

new_list = my_list

you are not copying the list, but assigning the reference to a new variable. What you need is

new_list = my_list[:]

my_list[:] actually creates a new copy in the memory. With that change, the program produces

replace Test
s, h, r, u, g, g, e, d
s, h, r, u, g, g, e, d
s, h, r, u, g, g, e, d

You can confirm whether the new copy is getting created or not using id in CPython.

new_list = my_list
print id(new_list), id(my_list)

will print the same address twice, which means that they both are pointing to the same element.

new_list = my_list[:]
print id(new_list), id(my_list)

will print two different addresses.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, I've been spending hours trying to fix this and it was something so small.
0

The best way to understand the difference is with some examples.

a = []
b = []

id(a)==id(b)
#False

a = []
b = a

id(a)==id(b)
#True

The id function simply returns the object’s unique id or object’s memory address.

Now to create a list with the same elements of a but with different id you can do the following:

a = [1,2,3,4,5]
#Both works
b = list(a) 
b = a[:]

id(a)==id(b)
#False

list() works with a generator, [:] doesn't. list() will construct a new list based on the sequence given. Most of the times list() can be replace by [:].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.