Списки в 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’]]
Python List .remove() — How to Remove an Item from a List in Python

Dionysia Lemonaki

In this article, you’ll learn how to use Python’s built-in remove() list method.
By the end, you’ll know how to use remove() to remove an item from a list in Python.
Here is what we will cover:
The remove() Method — A Syntax Overview
The remove() method is one of the ways you can remove elements from a list in Python.
The remove() method removes an item from a list by its value and not by its index number.
The general syntax of the remove() method looks like this:
Let’s break it down:
- list_name is the name of the list you’re working with.
- remove() is one of Python’s built-in list methods.
- remove() takes one single required argument. If you do not provide that, you’ll get a TypeError – specifically you’ll get a TypeError: list.remove() takes exactly one argument (0 given) error.
- value is the specific value of the item that you want to remove from list_name .
The remove() method does not return the value that has been removed but instead just returns None , meaning there is no return value.
If you need to remove an item by its index number and/or for some reason you want to return (save) the value you removed, use the pop() method instead.
How to Remove an Element from a List Using the remove() Method in Python
To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method.
remove() will search the list to find it and remove it.
If you specify a value that is not contained in the list, then you’ll get an error – specifically the error will be a ValueError :
To avoid this error from happening, you could first check to see if the value you want to remove is in the list to begin with, using the in keyword.
It will return a Boolean value – True if the item is in the list or False if the value is not in the list.
Another way to avoid this error is to create a condition that essentially says, «If this value is part of the list then delete it. If it doesn’t exist, then show a message that says it is not contained in the list».
Now, instead of getting a Python error when you’re trying to delete a certain value that doesn’t exist, you get a message returned, saying the item you wanted to delete is not in the list you’re working with.
The remove() Method Removes the First Occurrence of an Item in a List
A thing to keep in mind when using the remove() method is that it will search for and will remove only the first instance of an item.
This means that if in the list there is more than one instance of the item whose value you have passed as an argument to the method, then only the first occurrence will be removed.
Let’s look at the following example:
In the example above, the item with the value of Python appeared three times in the list.
When remove() was used, only the first matching instance was removed – the one following the JavaScript value and preceeding the Java value.
The other two occurrences of Python remain in the list.
What happens though when you want to remove all occurrences of an item?
Using remove() alone does not accomplish that, and you may not want to just remove the first instance of the item you specified.
How to Remove All Instances of an Item in A List in Python
One of the ways to remove all occurrences of an item inside a list is to use list comprehension.
List comprehension creates a new list from an existing list, or creates what is called a sublist.
This will not modify your original list, but will instead create a new one that satisfies a condition you set.
In the example above, there is the orginal programming_languages list.
Then, a new list (or sublist) is returned.
The items contained in the sublist have to meet a condition. The condition was that if an item in the original list has a value of Python , it would not be part of the sublist.
Now, if you don’t want to create a new list, but instead want to modify the already existing list in-place, then use the slice assignment combined with list comprehension.
With the slice assignment, you can modify and replace certain parts (or slices) of a list.
To replace the whole list, use the [:] slicing syntax, along with list comprehension.
The list comprehension sets the condition that any item with a value of Python will no longer be a part of the list.
Conclusion
And there you have it! You now know how to remove a list item in Python using the remove() method. You also saw some ways of removing all occurrences of an item in a list in Python.
I hope you found this article useful.
To learn more about the Python programming language, check out freeCodeCamp’s Scientific Computing with Python Certification.
You’ll start from the basics and learn in an interacitve and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you’ve learned.
Removing character in list of strings
What should I do in order to get rid of all the 8 s in each string? I tried using strip or replace in a for loop but it doesn’t work like it would in a normal string (that not in a list). Does anyone have a suggestion?
![]()
6 Answers 6
Beside using loop and for comprehension, you could also use map
A faster way is to join the list, replace 8 and split the new string:
Here’s a short one-liner using regular expressions:
If we separate the regex operations and improve the namings:
![]()
EDIT: For anyone who came across this post, just for understanding the above removes any elements from the list which are equal to 8.
Supposing we use the above example the first element («aaaaa8») would not be equal to 8 and so it would be dropped.
To make this (kinda work?) with how the intent of the question was we could perform something similar to this
- I am not in an interpreter at the moment so of course mileage may vary, we may have to index so we do list(y[0]) would be the only modification to the above for this explanation purposes.
What this does is split each element of list up into an array of characters so («aaaa8») would become [«a», «a», «a», «a», «8»].
This would result in a data type that looks like this
So finally to wrap that up we would have to map it to bring them all back into the same type roughly
I would absolutely not recommend it, but if you were really wanting to play with map and filter, that would be how I think you could do it with a single line.
Как удалить элемент из списка в Python
Рассказываем, как работают методы remove(), pop(), clear() и ключевое слово del.


Иллюстрация: Оля Ежак для Skillbox Media

В Python есть много удобных механизмов для работы со списками. И удалять элементы из них можно по-разному.
4 главных способа удалить элемент из списка
В этой статье мы рассмотрим четыре основных метода. Их функциональность в некоторых случаях пересекается, поэтому иногда они вполне взаимозаменяемы.
Метод remove(): удаление по значению
remove() можно использовать, когда мы точно знаем значение, от которого хотим избавиться. В качестве аргумента remove() получает объект, находит совпадение и удаляет его, ничего не возвращая:
Можно удалять и более сложные объекты: например, внутренние списки. Главное — в точности передать этот объект методу:
remove() удаляет только первое совпадение с искомым элементом. Например, так он себя поведёт, если в списке будет несколько строк ‘ноль’:
При попытке удалить значение, которого нет в списке, Python выдаст ошибку ValueError.
Метод pop(): удаление по индексу
pop() подойдёт, когда известно точное местоположение удаляемого элемента. В качестве аргумента pop() получает индекс, а возвращает удалённое значение:
Если передать отрицательное значение, то pop() будет считать индексы не с нуля, а с -1:
А вот если оставить pop() без аргумента, то удалится последний элемент — потому что -1 является аргументом по умолчанию:
При попытке обратиться в методе pop() к несуществующему индексу, интерпретатор выбросит исключение IndexError.
Метод clear(): очищение списка
clear() удаляет из списка всё, то есть буквально очищает его. Он не принимает аргументов и не возвращает никаких значений:
Ключевое слово del: удаление срезов
del, как и метод pop(), удаляет элементы списка по индексу. При этом с его помощью можно избавиться как от единичного объекта, так и от целого среза:
Если передать срез, то элемент с правым индексом не удалится. В примере ниже это строка ‘IV’:
Чтобы очистить список, достаточно передать полный срез [:]:
Также del можно использовать с отрицательными индексами:
Со срезами это тоже работает:
Если при удалении единичного элемента указать несуществующий индекс, то Python выдаст ошибку IndexError.
Как удалить первый элемент списка в Python
Довольно часто, например, при реализации стека, нужно удалить первый элемент списка. Возьмём наш new_list и посмотрим, какими способами это можно сделать.
С помощью метода pop(0)
Передаём в качестве аргумента pop() индекс 0:
С помощью ключевого слова del
Используем del с элементом с индексом 0.
Как удалить несколько элементов
Если элементы, от которых нужно избавиться, находятся по соседству друг с другом, то удобнее всего использовать del.
Допустим, в последовательности чисел от 0 до 9 нужно удалить 4, 5, 6 и 7. Тогда решение будет выглядеть так:
Как удалить последний элемент списка в Python
Если мы хотим избавиться от последнего элемента, то, как и в случае с первым, удобнее всего это сделать с помощью pop() или del.
С помощью метода pop()
Так как по умолчанию метод принимает аргумент -1, то можно вообще ничего не передавать:
Но если вы истинный приверженец дзена Python («Явное лучше неявного»), то можно указать -1 — ничего не изменится.
С помощью ключевого слова del
А вот если хотите удалить последний элемент с помощью del, то передать -1 нужно обязательно:
Подведём итоги
Язык Python даёт четыре основных инструмента для удаления элементов из списка: