list.clear()
list.clear() None · Updated March 13, 2026 · List Methods The .clear() method removes all elements from a list, leaving it empty. The list object itself remains — it’s just emptied out. This is useful when you need to reset a list for reuse without creating a new object.
Syntax
list.clear()
Parameters
None. This method takes no parameters.
Examples
Basic usage
Clear all elements from a list:
numbers = [1, 2, 3, 4, 5]
numbers.clear()
print(numbers)
# []
Resetting a list in a loop
A common pattern involves clearing and repopulating a list across iterations:
results = []
for batch in data_batches:
results.clear() # Reset for next batch
for item in batch:
if item.is_valid():
results.append(item.process())
print(f"Batch results: {results}")
Clearing vs reassigning
There are two ways to empty a list:
my_list = [1, 2, 3]
# Method 1: .clear() — modifies in-place
my_list.clear()
# my_list is now []
# Method 2: Reassign to empty list
my_list = [1, 2, 3]
my_list = []
The key difference: .clear() modifies the original list object, while reassignment creates a new object. This matters when other variables reference the same list:
original = [1, 2, 3]
copy = original
original.clear() # Both variables see the change
print(copy)
# []
# With reassignment, 'copy' keeps the old data
original = [1, 2, 3]
copy = original
original = [] # 'original' now points to new empty list
print(copy)
# [1, 2, 3]
Clearing with conditional logic
Sometimes you want to selectively clear:
buffer = ["item1", "item2", "item3"]
if some_condition:
buffer.clear()
print("Buffer cleared")
else:
print(f"Buffer has {len(buffer)} items")
Common Patterns
Implementing a cache
Use .clear() to reset a cache:
cache = []
def get_cached_data(key):
for item in cache:
if item.key == key:
return item.value
return None
def clear_cache():
cache.clear()
print("Cache cleared")
Processing in batches
Clear a list between batches of work:
batch_results = []
for chunk in large_dataset:
batch_results.clear()
for item in chunk:
processed = transform(item)
batch_results.append(processed)
save_batch(batch_results)
Temporary storage
Use a list as temporary workspace and clear it when done:
temp_storage = []
def add_item(item):
temp_storage.append(item)
def reset_temp():
temp_storage.clear()
# ... use temp_storage ...
reset_temp() # Clean up when finished
Performance Note
.clear() is O(n) because it needs to release references to all n elements, allowing the garbage collector to reclaim that memory. If you’re just discarding all elements, reassigning to [] is slightly faster (O(1)) because it doesn’t iterate:
# Slower: O(n)
my_list.clear()
# Faster: O(1)
my_list = []
However, use .clear() when you need to preserve the same list object reference.
See Also
- list::list.append() — add elements to a list
- list::list.pop() — remove and return an element
- list::list — the list constructor
- built-in::len — get the length of a list