0
0
PythonHow-ToBeginner · 3 min read

How to Clear a List in Python: Simple Methods Explained

To clear a list in Python, use the clear() method which removes all items from the list. Alternatively, you can assign an empty list [] or use slicing like list[:] = [] to empty the list.
📐

Syntax

There are three common ways to clear a list in Python:

  • list.clear(): Removes all items from the list in place.
  • list[:] = []: Replaces all elements with an empty list using slicing.
  • list = []: Assigns a new empty list to the variable (does not affect other references).
python
my_list.clear()
💻

Example

This example shows how to clear a list using the clear() method and slicing. It prints the list before and after clearing.

python
my_list = [1, 2, 3, 4, 5]
print("Before clearing:", my_list)

my_list.clear()
print("After clear():", my_list)

my_list = [1, 2, 3, 4, 5]
my_list[:] = []
print("After slicing clear:", my_list)
Output
Before clearing: [1, 2, 3, 4, 5] After clear(): [] After slicing clear: []
⚠️

Common Pitfalls

A common mistake is using list = [] to clear a list when other variables reference the same list. This only reassigns the variable and does not clear the original list object.

Use clear() or slicing to modify the list in place if you want all references to see the change.

python
original_list = [1, 2, 3]
copy_list = original_list

original_list = []  # This only reassigns original_list
print(copy_list)    # Output: [1, 2, 3]

# Correct way:
original_list = [1, 2, 3]
copy_list = original_list
original_list.clear()  # Clears the list in place
print(copy_list)       # Output: []
Output
[1, 2, 3] []
📊

Quick Reference

MethodEffectModifies Original List?
list.clear()Removes all items in placeYes
list[:] = []Replaces all items with empty listYes
list = []Assigns new empty list to variableNo

Key Takeaways

Use list.clear() to empty a list while keeping the same list object.
Slicing with list[:] = [] also clears the list in place.
Assigning list = [] creates a new list and does not affect other references.
Choose clear() or slicing when multiple variables reference the same list.
Clearing a list removes all its elements, making it empty.