Списки в 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’]]
Методы append() и extend() в Python: добавляем элементы в список
Учимся работать со списками с помощью встроенных функций языка.


Иллюстрация: Катя Павловская для Skillbox Media

Методы append() и extend() позволяют добавить новый элемент в уже существующий список или объединить несколько list-объектов в один. В этой статье мы расскажем и покажем на примерах, как ими пользоваться. А в конце — поделимся менее очевидными способами расширения списков.
Что делает append() в Python
append() добавляет в конец списка элемент, переданный ему в качестве аргумента. Как и все методы в Python, он вызывается через оператор . (точка).
Синтаксис и возвращаемое значение
append() принимает один аргумент item и добавляет его в конец list. Тип параметра может быть любым: числа, строки, словари и так далее. Метод возвращает объект None — то есть ничего.
Примеры использования append()
Допустим, у нас есть список a, который заполнен строками:
Если мы захотим добавить в него новую строку ‘row’, то передадим её в качестве аргумента в append(). Так как метод принадлежит типу list, то вызывать его нужно для объекта a через точку:
Строка добавилась в конец нашего списка. Всё работает.
Усложним задачу и попробуем добавить ещё один список из двух строк:
Как мы видим, в a добавился список b с вложенными в него элементами. А если мы захотим, чтобы элементы из b добавились отдельно? Вот так:
К сожалению, с помощью append() этого сделать нельзя, потому что метод принимает только один аргумент. Если вы всё-таки попытаетесь передать несколько объектов через запятую, то интерпретатор вызовет исключение TypeError (ошибка типа):
К счастью, есть метод extend(), который позволяет добавить одновременно несколько элементов. О нём и поговорим далее.
Что делает extend() в Python
extend() принимает в качестве параметра итерируемый объект и объединяет его со списком.
Синтаксис и возвращаемое значение
extend() добавляет новые элементы в конец списка, но, в отличие от append(), принимает в качестве параметров итерируемые объекты: списки, кортежи и строки. При этом объединяемые списки могут содержать элементы любых типов: например, вы можете объединить строки с числами или числа с кортежами.
Как и append(), метод возвращает объект None.
Примеры использования extend()
Вернёмся к нашему списку a:
Допустим, мы хотим соединить его с другим списком из строк. Передадим b в extend() и получим результат:
Как видите, каждый элемент из b по отдельности добавился в a.
Мы можем сделать то же самое и с другим итерируемыми объектами — например, кортежами или строками:
Обратите внимание: строки, которые передаются в extend(), превращаются в списки символов и добавляются посимвольно. Так, строка ‘man’ разложилась на ‘m’, ‘a’, ‘n’.
Если передать в extend() не итерируемый объект, например число, Python генерирует TypeError:
В сообщении нам вежливо объясняют, что число — это не итерируемый объект.
Как ещё можно добавить элементы в список
Чтобы упростить жизнь питонистам, разработчики языка добавили пару фич, которые помогают быстро добавлять элементы в списки.
Оператор +. Он напоминает обычный математический оператор, но со списками действует как функция extend():
Все элементы одного списка добавились в конец другого.
Срезы. Ещё один способ добавить элементы в список — нестандартно использовать индексацию. Выглядит это так:
Выглядит немного странно, но это действительно работает. Когда мы пытаемся обратиться к несуществующим элементам a, язык добавляет новые элементы из списка b, ссылку на который мы передали справа от оператора присваивания.
Python List extend() Method
![]()
In Python, the list.extend() method is used to iterate over an iterable (string, tuple, list, set, or dictionary) and then add each element of the iterable to the end of the current list. The length of the list increases by the number of elements present in the iterable.
Syntax of extend() in Python
The syntax of the extend() method in Python is:
The list extend() method is written with the list to be extended and an iterable is passed to it.
Parameters of extend() in Python
The list extend() method has only one parameter, an iterable . The iterable can be a list, tuple (it is like an immutable list), string, set, or even a dictionary.
Return Values from extend()
The list extend() method doesn't return anything, it just modifies the given list.
Python List extend() Example
Code:
Output:
Explanation:
In the above example, we are adding the list swiss_watches to the end of the list watches using the list extend() method.
What is extend() in Python?
The list.extend() is Python's built-in function. It iterates over the specified iterable and appends its elements to the end of the current list. The list.extend() method is equivalent to list[len(list):] = iterable (appends the elements of the iterable after the list's last element).
How to Use the List extend() Method in Python?
We can use extend in Python by passing any iterable as an argument to it, be it a list, tuple, string, set, or dictionary.
Using the List extend() Method with a List
When we use the list extend() method with a list ( my_list ), all the elements of my_list gets added at the end of the current list.
Using the List extend() Method with a Tuple
When we use the list extend() method with a tuple ( my_tuple ), it behaves similarly to a list as all the elements of my_tuple gets added at the end of the current list too.
Using the List extend() Method with a String
When we use the list extend() method with a string ( my_str ), all the characters of my_str gets added at the end of the current list as different elements.
Using the List extend() Method with a Set
When we use the list extend() method with a set ( my_set ), it behaves similarly to a list as all the elements of my_list gets added at the end of the current list.
Using the List extend() Method with a Dictionary
When we use the list extend() method with a dictionary ( my_dict ), all the keys of my_dict gets added at the end of the current list as list elements. Instead of adding keys to the dictionary, we can also add its values at the end of the current list by passing the my_dict.values() to the list extend() method.
Differences between append() and extend() in Python
The list extend() method in Python is used to add the elements of the iterable at the end of the current list as list elements. The length of the iterable increases the length of the original list.
On the other hand, the list append() method is used to add the object at the end of the current list as a single element. The length of the original list is increased by 1.
This comparison below will help in better understanding of the difference between the two:
| list.extend() | list.append() |
|---|
More Examples
Example 1: Adding elements to a List Using Another List
Code:
Output:
Explanation:
In the above example, we are adding the items of list y at the end of the list x using the list.extend() method.
Example 2: Adding Elements to a List Using a Tuple
Code:
Output:
In the above example, we add the items of tuple y at the end of the list x using the list.extend() method.
Example 3: Adding Elements to a List Using a String
Code:
Output:
Explanation:
In the above example, we are adding the characters of the string y at the end of the list x as different list elements using the list.extend() method.
Example 4: Adding Elements to a List Using a Set
Code:
Output:
Explanation:
In the above example, we are adding the elements of the set y at the end of the list x using the list.extend() method.
Example 5: Adding Elements to a List Using a Dictionary's Keys
Code:
Output:
Explanation:
In the above example, we are adding the keys of the dictionary y at the end of the list x using the list.extend() method.
To add the values of a dictionary, we can use dictionary.values() .
Example 6: Adding elements to a List Using a Dictionary's Values
Code:
Output:
Explanation:
In the above example, we are adding the values of the dictionary y.values() at the end of the list x using the list.extend() method.
Example 7: Extending a List Using the list-slicing Technique
Code:
Output:
Explanation:
In the above example, we are adding the items of list y at the end of the list x using the list slicing technique (the items of y get added from the len(x) index in the list x ).
Python Lists
![]()
There are four collection data types in the Python programming language:
- List is a collection which is ordered and changeable. Allows duplicate members.
- Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
- Set is a collection which is unordered and un-indexed. No duplicate members.
- Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.
Python Lists
- A list is a collection which is ordered and changeable.
- In Python lists are written with square brackets.
- It is a data structure which is used to store various types of data in python.
- Lists are mutable that is we can change any value in the list.
- Lists can hold any type of data which means it can store strings,int s well as float values in a single list
Let us put all the data types in a single list.For example,
Accessing values in the List
You access the list items by referring to the index number. Let us take a list with all the string values in it.
Representation of list, lst is name of the list. apple,banana, cherry are the values in the list. Below is their indexing and values stored in the list.
Python supports negative indexing. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.
Slice Operator:
- To retrieve some of the values in the list, Python supports slice operator.
- You can specify a range of indexes by specifying where to start and where to end the range.
- When specifying a range, the return value will be a new list with the specified items.
- Syntax: [ start : end ]
- In slice Operator, start is included and end is excluded.
Note: The search will start at index 2 (included) and end at index 5 (not included) and the first index starts from 0.
When we leave out the start value of slice operator, the range will start at the first item:
When we leave out the endvalue of slice operator, the range will start from the specified index till the end:
We can Specify negative indexes if you want to start the search from the end of the list:
- Lists are mutable. That means we can change a specific value in the list.
The above code is used to change a specific value in the list. That is, the value at the index 1 will be changed from 20 to 70.
Using for loop to display the values in the list:
To determine if a specified item is present in a list we can use the in keyword which is supported by python:
List Length
To determine the number of items present in the list, use the len() function: