Skip to content Skip to sidebar Skip to footer

Difference Between Arr[:]=[] And Arr[]=[] In Python3.x?

Is there any difference between these two lines: arr[:] = [] arr = [] I know both of them clear list.

Solution 1:

For the second one, I think you meant arr = [].

What that does differently is that it has arr point to a new empty list and just decrements the refcount on the existing list.

The difference is only important if something else is pointing to the original list.

>>>orig = [10, 20, 30]>>>arr = orig              # Second reference to the same list.>>>arr[:] = []             # Clears the one list, so that arr and orig are empty>>>orig
[]

Contrast that with:

>>>orig = [10, 20, 30]>>>arr = orig              # Second reference to the same list.>>>arr = []                # Points arr to a new list, leaving orig unchanged>>>orig
[10, 20, 30]

Post a Comment for "Difference Between Arr[:]=[] And Arr[]=[] In Python3.x?"