Home > front end >  python list cleared while clearing another list
python list cleared while clearing another list

Time:11-18

I'm currently writing a python skript and I have an issue that a list is getting cleared if I clear another list.

elements is a list that is filled before

elements2 = elements
while len(elements2) > 0:
    
    elements2.clear()
    print(elements)
    function(elements, elements2)

When i print elements the list is empty. This is critical because my function has a for-loop going through elements and putting some parts of the list in elements2 in some occasions so the funtion stops being declared only when all Parameters are set for it.

Why is elements cleared when I clear elements2 and how do i prevent it but still clear elements2?

Thanks in advance

CodePudding user response:

when you assign elements2 to elements you arent copying the list instead elements2 references the same list as elements so changes to one affects the other. Use elements2 = elements.copy() to create a copy of the original

CodePudding user response:

Python lists are copied by reference, not by value. This means that when you set elements2 equal to elements, you are setting them both to point to the same area in memory. That is why changes to elements2 will also apply to elements. To combat this, you can use the copy module, or that you can use the following line to get the same result: elements2 = list(elements)

This creates a copy of elements, but note that this isn't a deep copy - meaning that if elements contains lists or other types that are copied by reference, the values from both elements and elements2 will point to the same object.

  • Related