-1

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

Simon
  • 19
  • 1
  • 4
  • 2
    `elements2 = elements` does not make a copy of `elements`. You need to explicitly call the `.copy()` method: `elements2 = elements.copy()` for a (shallow) copy – rdas Nov 18 '21 at 11:18
  • python arrays are assigned by reference. https://stackoverflow.com/questions/41770791/arrays-in-python-are-assigned-by-value-or-by-reference – Mani Nov 18 '21 at 11:19

2 Answers2

1

when you assign elements2 to elements you aren't 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

ImSo3K
  • 792
  • 7
  • 21
1

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.

Gderu
  • 131
  • 8