Перейти к содержимому

Как очистить массив в python

  • автор:

4 Ways to Clear a Python List

Python Clear List Cover Image

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

Quick Answer - Python Clear List

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.

How does Python List Indexing Work

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:

  1. We instantiated a list
  2. We then applied the clear method to empty the list
  3. 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:

  1. We instantiated a Python list, items
  2. We then used the del keyword to delete items from the first to the last index
  3. 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?

martineau's user avatar

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’]]

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *