4 Ways to Clear a Python List

In this tutorial, you’ll learn four different ways to use Python to clear a list. You’ll learn how to use the clear method, the del statement, the *= operator, and list item re-assignment. Knowing how to clear a list is a task that should seem easy, but is an often elusive skill. After reading this tutorial, you’ll have learned four different ways to clear a Python list in order to start fresh.
The Quick Answer: Use clear

Table of Contents
What are Python Lists?
Lists in Python are one of the main data structures that exist in the language. They have some unique attributes, similar to arrays in other languages. They can hold values of different data types, meaning that they’re heterogeneous. They are also ordered, meaning that you can access the items by their index position. Python list indices start at 0 and increment by 1. Python lists can also contain duplicate values.

In the next section, you’ll learn how to clear a Python list with the .clear() method.
Clear a Python List with Clear
One of the easiest ways to clear a Python list is to the use the list.clear() method. The method empties a given list and doesn’t return any items. The method was introduced in Python 3.2, so if you’re using an earlier version, you’ll need to read on to learn how to use the del operator.
Let’s see how we can empty a list by using the clear method:
Let’s break down what we did above:
- We instantiated a list
- We then applied the clear method to empty the list
- We print the list to ensure that the list is emptied
Now that we know how to use the clear method, we can explore some additional properties about it. The method doesn’t accept any arguments and it modifies a list in place (meaning that we don’t re-assign it to another list).
In the next section, you’ll learn how to empty a Python list with the del keyword.
Want to learn how to pretty print a JSON file using Python? Learn three different methods to accomplish this using this in-depth tutorial here.
Clear a Python List with del
The Python del keyword allows us to delete a particular list item or a range of list items at particular indices. If you want to learn how to use the Python del keyword to delete list items, check out my in-depth tutorial here. Since we can use the Python del keyword to delete items or ranges of items in a list, we can simply delete all items in the list using the : operator.
Let’s see how we can use the del keyword to empty a Python list:
Let’s break down what we did here:
- We instantiated a Python list, items
- We then used the del keyword to delete items from the first to the last index
- We then printed the list to make sure it was empty
Interestingly, the .clear() method works exactly the same as the del [:] keyword, under the hood. It really just represents syntactical sugar in order to make the process a little easier to understand.
In the next section, you’ll learn how to empty a Python list using the *= operator.
Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!
Clear a Python List with the *= Operator
Python allows us to chain operators together. For example, writing a = a + 1 is the same as writing a += 1 . Another way to chain operators is to use the *= , which reassigns the variable multiplied by zero. When we apply this operator a list, we assign the value of 0 to each item, thereby removing the items from the list.
Let’s see how we can use the *= operator to empty a Python list of all of its elements:
In the next section, you’ll learn how to use Python to empty a list using list item re-assignment.
Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.
Clear a Python List with List Item Re-assignment
While it may seem intuitive to empty a list simply by writing some_list = [] . This approach doesn’t actually delete the items from the list, it just removes the reference to the items. If the list has also been assigned to another variable, it’ll be retained in memory.
We can, however, assign the full range of items to be empty items. This will delete all of the items in a list, thereby clearing it.
Let’s see how we can do this with Python:
In the example above, we can see that we re-assigned all of the list items by using the list indexing method. We were able to access all of the items and assign them an empty value.
Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.
Conclusion
In this tutorial, you learned four different ways to use Python to clear a list. You learned how to use the .clear() method, the del keyword, the *= operator, and list item re-assignment. Being able to work with lists in different ways is an important skill for a Pythonista of any level.
To learn more about Python lists, check out the official documentation here.
How to empty a list?
![]()
This actually removes the contents from the list, but doesn’t replace the old label with a new empty list:
Here’s an example:
For the sake of completeness, the slice assignment has the same effect:
It can also be used to shrink a part of the list while replacing a part at the same time (but that is out of the scope of the question).
Note that doing lst = [] does not empty the list, just creates a new object and binds it to the variable lst , but the old list will still have the same elements, and effect will be apparent if it had other variable bindings.
Как очистить массив в python
Time Complexity: O(1)
Auxiliary Space: O(1)
Method #2: Reinitializing the list:
The initialization of the list in that scope initializes the list with no value. i.e list of size 0. Let’s see the example demonstrating Method 1 and 2 to clear list.
Python3
Time complexity: O(1)
Auxiliary space: O(1)
Method #3: Using “*= 0” : This is a lesser-known method, but this method removes all elements of the list and makes it empty.
Python3
Time complexity: O(1) for both clear() and reinitialization
Auxiliary space: O(1) for both clear() and reinitialization
Method #4: Using del : del can be used to clear the list elements in a range, if we don’t give a range, all the elements are deleted.
Python3
Time Complexity: O(1)
Auxiliary Space: O(1)
Method #5 : Using pop() method
Python3
The time complexity of the given Python code is O(n^2) where n is the length of the list list1.
space complexity of the code is constant, i.e., O(1).
Method #5: Using slicing
This method involves using slicing to create a new list with no elements, and then assigning it to the original list variable.
Списки в Python
Всем привет! В этой статье мы познакомимся с методами для работы со списками в python . Но сначала вспомним, что такое список? Список — это изменяемый и последовательный тип данных. Это значит, что мы можем добавлять, удалять и изменять любые элементы списка.
Начнем с метода append() , который добавляет элемент в конец списка:
# Создаем список, состоящий из четных чисел от 0 до 8 включительно
numbers = list ( range ( 0 , 10 , 2 ))
# Добавляем число 200 в конец списка
numbers. append ( 200 )
print (numbers)
# [0, 2, 4, 6, 8, 200]
numbers. append ( 1 )
numbers. append ( 2 )
numbers. append ( 3 )
print (numbers)
# [0, 2, 4, 6, 8, 200, 1, 2, 3]
Мы можем передавать методу append() абсолютно любые значения:
all_types = [ 10 , 3.14 , ‘Python’ , [ ‘I’ , ‘am’ , ‘list’ ]]
all_types. append ( 1024 )
all_types. append ( ‘Hello world!’ )
all_types. append ([ 1 , 2 , 3 ])
print (all_types)
# [10, 3.14, ‘Python’, [‘I’, ‘am’, ‘list’], 1024, ‘Hello world!’, [1, 2, 3]]
Метод append() отлично выполняет свою функцию. Но, что делать, если нам нужно добавить элемент в середину списка? Это умеет метод insert () . Он добавляет элемент в список на произвольную позицию. insert() принимает в качестве первого аргумента позицию, на которую нужно вставить элемент, а вторым — сам элемент.
# Создадим список чисел от 0 до 9
numbers = list ( range ( 10 ))
# Добавление элемента 999 на позицию с индексом 0
numbers. insert ( 0 , 999 )
print (numbers)
# [999, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers. insert ( 2 , 1024 )
print (numbers)
# [999, 0, 1024, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers. insert ( 5 , ‘Засланная строка-шпион’ )
print (numbers)
# [999, 0, 1024, 1, 2, ‘Засланная строка-шпион’, 3, 4, 5, 6, 7, 8, 9]
Отлично! Добавлять элементы в список мы научились, осталось понять, как их из него удалять. Метод pop() удаляет элемент из списка по его индексу:
numbers = list ( range ( 10 ))
print (numbers)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Удаляем первый элемент
numbers. pop ( 0 )
print (numbers)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers. pop ( 0 )
print (numbers)
# [2, 3, 4, 5, 6, 7, 8, 9]
numbers. pop ( 2 )
print (numbers)
# [2, 3, 5, 6, 7, 8, 9]
# Чтобы удалить последний элемент, вызовем метод pop без аргументов
numbers. pop ()
print (numbers)
# [2, 3, 5, 6, 7, 8]
numbers. pop ()
print (numbers)
# [2, 3, 5, 6, 7]
Теперь мы знаем, как удалять элемент из списка по его индексу. Но что, если мы не знаем индекса элемента, но знаем его значение? Для такого случая у нас есть метод remove() , который удаляет первый найденный по значению элемент в списке.
all_types = [ 10 , ‘Python’ , 10 , 3.14 , ‘Python’ , [ ‘I’ , ‘am’ , ‘list’ ]]
all_types. remove ( 3.14 )
print (all_types)
# [10, ‘Python’, 10, ‘Python’, [‘I’, ‘am’, ‘list’]]
all_types. remove ( 10 )
print (all_types)
# [‘Python’, 10, ‘Python’, [‘I’, ‘am’, ‘list’]]
all_types. remove ( ‘Python’ )
print (all_types) # [10, ‘Python’, [‘I’, ‘am’, ‘list’]]
А сейчас немного посчитаем, посчитаем элементы списка с помощью метода count()
numbers = [ 100 , 100 , 100 , 200 , 200 , 500 , 500 , 500 , 500 , 500 , 999 ]
print (numbers. count ( 100 ))
# 3
print (numbers. count ( 200 ))
# 2
print (numbers. count ( 500 ))
# 5
print (numbers. count ( 999 ))
# 1
В программировании, как и в жизни, проще работать с упорядоченными данными, в них легче ориентироваться и что-либо искать. Метод sort() сортирует список по возрастанию значений его элементов.
numbers = [ 100 , 2 , 11 , 9 , 3 , 1024 , 567 , 78 ]
numbers. sort ()
print (numbers)
# [2, 3, 9, 11, 78, 100, 567, 1024]
fruits = [ ‘Orange’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Apple’ ]
fruits. sort ()
print (fruits)
# [‘Apple’, ‘Banan’, ‘Grape’, ‘Orange’, ‘Peach’]
Мы можем изменять порядок сортировки с помощью параметра reverse . По умолчанию этот параметр равен False
fruits = [ ‘Orange’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Apple’ ]
fruits. sort ()
print (fruits)
# [‘Apple’, ‘Banan’, ‘Grape’, ‘Orange’, ‘Peach’]
fruits. sort ( reverse = True )
print (fruits)
# [‘Peach’, ‘Orange’, ‘Grape’, ‘Banan’, ‘Apple’]
Иногда нам нужно перевернуть список, не спрашивайте меня зачем. Для этого в самом лучшем языке программирования на этой планете JavaScr..Python есть метод reverse() :
numbers = [ 100 , 2 , 11 , 9 , 3 , 1024 , 567 , 78 ]
numbers. reverse ()
print (numbers)
# [78, 567, 1024, 3, 9, 11, 2, 100]
fruits = [ ‘Orange ‘, ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Apple’ ]
fruits. reverse ()
print (fruits)
# [‘Apple’, ‘Banan’, ‘Peach’, ‘Grape’, ‘Orange’]
Допустим, у нас есть два списка и нам нужно их объединить. Программисты на C++ cразу же кинулись писать циклы for , но мы пишем на python , а в python у списков есть полезный метод extend() . Этот метод вызывается для одного списка, а в качестве аргумента ему передается другой список, extend() записывает в конец первого из них начало второго:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
vegetables = [ ‘Tomato’ , ‘Cucumber’ , ‘Potato’ , ‘Carrot’ ]
fruits. extend (vegetables)
print (fruits)
# [‘Banana’, ‘Apple’, ‘Grape’, ‘Tomato’, ‘Cucumber’, ‘Potato’, ‘Carrot’]
В природе существует специальный метод для очистки списка — clear()
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
vegetables = [ ‘Tomato’ , ‘Cucumber’ , ‘Potato’ , ‘Carrot’ ]
fruits. clear ()
vegetables. clear ()
print (fruits)
# []
print (vegetables)
# []
Осталось совсем чуть-чуть всего лишь пара методов, так что делаем последний рывок! Метод index() возвращает индекс элемента. Работает это так: вы передаете в качестве аргумента в index() значение элемента, а метод возвращает его индекс:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
print (fruits. index ( ‘Apple’ ))
# 1
print (fruits. index ( ‘Banana’ ))
# 0
print (fruits. index ( ‘Grape’ ))
# 2
Финишная прямая! Метод copy() , только не падайте, копирует список и возвращает его брата-близнеца. Вообще, копирование списков — это тема достаточно интересная, давайте рассмотрим её по-подробнее.
Во-первых, если мы просто присвоим уже существующий список новой переменной, то на первый взгляд всё выглядит неплохо:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
new_fruits = fruits
print (fruits)
# [‘Banana’, ‘Apple’, ‘Grape’]
print (new_fruits)
# [‘Banana’, ‘Apple’, ‘Grape’]
Но есть одно маленькое «НО»:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
new_fruits = fruits
fruits. pop ()
print (fruits)
# [‘Banana’, ‘Apple’]
print (new_fruits)
# Внезапно, из списка new_fruits исчез последний элемент
# [‘Banana’, ‘Apple’]
При прямом присваивании списков копирования не происходит. Обе переменные начинают ссылаться на один и тот же список! То есть если мы изменим один из них, то изменится и другой. Что же тогда делать? Пользоваться методом copy() , конечно:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
new_fruits = fruits. copy ()
fruits. pop ()
print (fruits)
# [‘Banana’, ‘Apple’]
print (new_fruits)
# [‘Banana’, ‘Apple’, ‘Grape’]
Отлично! Но что если у нас список в списке? Скопируется ли внутренний список с помощью метода copy() — нет:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ , [ ‘Orange’ , ‘Peach’ ]]
new_fruits = fruits. copy ()
fruits[ — 1 ]. pop ()
print (fruits)
# [‘Banana’, ‘Apple’, ‘Grape’, [‘Orange’]]
print (new_fruits)
# [‘Banana’, ‘Apple’, ‘Grape’, [‘Orange’]]