Python List clear()

The clear() method removes all items from the list.

Example

prime_numbers = [2, 3, 5, 7, 9, 11]

# remove all elements
prime_numbers.clear()

# Updated prime_numbers List print('List after clear():', prime_numbers)
# Output: List after clear(): []

Syntax of List clear()

The syntax of clear() method is:

list.clear()

clear() Parameters

The clear() method doesn't take any parameters.


Return Value from clear()

The clear() method only empties the given list. It doesn't return any value.


Example 1: Working of clear() method

# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]

# clearing the list list.clear()
print('List:', list)

Output

List: []

Note: If you are using Python 2 or Python 3.2 and below, you cannot use the clear() method. You can use the del operator instead.


Example 2: Emptying the List Using del

# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]

# clearing the list del list[:]
print('List:', list)

Output

List: []

To learn more about the del operator, visit Python del Statement.


Also Read:

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community