Clear a list

20 August 2020

Code

Caution !!!: Clearing a list may affect other references to the list.

Using .clear():

# Create a list
x = [1,2,3]
y = x # reference

# Clear 
x.clear()

# Output
print('x =',x)
print(type(x), '\n')
print('Check!')
print('y =',y)
x = []
<class 'list'> 

Check!
y = []

.

Using [ ]:

# Create a list
x = [1,2,3]
y = x # reference

# Clear 
x = []

# Output
print('x =',x)
print(type(x), '\n')
print('Check!')
print('y =',y)
x = []
<class 'list'> 

Check!
y = [1, 2, 3]

.

Using del:

# Create a list
x = [1,2,3]
y = x # reference

# Clear 
del x[:]

# Output
print('x =',x)
print(type(x), '\n')
print('Check!')
print('y =',y)
x = []
<class 'list'> 

Check!
y = []

.






Any errors in code above?
Please send a message.