Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Confused with changing lists

I’m stuck on this weird thing in Python where changing one thing messes with another. But with other variables it works fine.

How do I fix this?

example = [1, 2, 3,4,5]
new = example
new[3] = 6
print(example)

Which outputs [1, 2, 3, 6, 5] instead of [1,2,3,4,5]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you set new = example, you’re essentially making both of them refer to the exact same memory location. Hence any change made to one will be seen in the other.
We can correct this with

new = example[:]

Although in some cases you need to

import copy
new = deepcopy(example)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading