Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I want to:

create a copy of a global list that already exists,

modify the contents of this new list without affecting the original one,

print both lists

all inside a function.

My code:

original_list = ['tom', 'adam', 'john']

def a():

    new_list = original_list

    new_list[1] = 'simon'

    print(original_list, new_list)

a()

Expected result:

['tom', 'adam', 'john'] ['tom', 'simon', 'john']

Actual result:

['tom', 'simon', 'john'] ['tom', 'simon', 'john']

Please explain why my code behaves the way it does and not as I expect it to.

Thanks in advance!

1 Answer

0 votes
by (25.1k points)

This is caused because you are not copying the list but pointing to the same list with a different variable.

If you are using Python3.3+ you can use the method copy on the original array when assigning it to the new variable. If not you can try slicing it list[:].

Browse Categories

...