What is the difference between list = []
and list.clear()
?
Base on the behavior of my code and my own observation, list.clear()
removes its entries and also the entries I used to append its data.
Example:
container.append(list)
list.clear()
container
will also be []
Calling clear
removes all the element from the list. Assigning []
just replaces that variable with another empty list. This becomes evident when you have two variables pointing to the same list.
Consider the following snippet:
>>> l1 = [1, 2, 3]
>>> l2 = l1
>>> l1.clear()
>>> l1 # l1 is obviously empty
[]
>>> l2 # But so is l2, since it's the same object
[]
As compared to this one:
>>> l1 = [1, 2, 3]
>>> l2 = l1
>>> l1 = []
>>> l1 # l1 is obviously empty
[]
>>> l2 # But l2 still points to the previous value, and is not affected
[1, 2, 3]
You can also see this if you take a look at the bytecode that is generated. Here the part with x = []
import dis
print("Example with x = []")
s1 = """
x = [1,2,3]
x = []
"""
dis.dis(s1)
which outputs
Exmaple with x = []
2 0 LOAD_CONST 0 (1)
2 LOAD_CONST 1 (2)
4 LOAD_CONST 2 (3)
6 BUILD_LIST 3
8 STORE_NAME 0 (x)
3 10 BUILD_LIST 0
12 STORE_NAME 0 (x)
14 LOAD_CONST 3 (None)
16 RETURN_VALUE
we can see that two lists are build since we have two BUILD_LIST
. Now if we take a look at x.clear()
print("Exmaple with x.clear()")
s2 = """
x = [1,2,3]
x.clear()
"""
dis.dis(s2)
we get the following output
Exmaple with x.clear()
2 0 LOAD_CONST 0 (1)
2 LOAD_CONST 1 (2)
4 LOAD_CONST 2 (3)
6 BUILD_LIST 3
8 STORE_NAME 0 (x)
3 10 LOAD_NAME 0 (x)
12 LOAD_ATTR 1 (clear)
14 CALL_FUNCTION 0
16 POP_TOP
18 LOAD_CONST 3 (None)
20 RETURN_VALUE
and here only one list is build and clear is called and LOAD_CONST
is used to place None
onto the stack as with the initial values 1,2,3
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With