- Методы append() и extend() в Python: добавляем элементы в список
- Что делает append() в Python
- Синтаксис и возвращаемое значение
- Примеры использования append()
- Что делает extend() в Python
- Синтаксис и возвращаемое значение
- Примеры использования extend()
- Как ещё можно добавить элементы в список
- Что запомнить
- Python List .append() – How to Add an Item to a List in Python
- Prerequisites
- Lists in Python
- How to create a list in Python
- How to access items in a list
- How to find the length of a list
- Methods to Add Items to a List
- How to insert items in a list with insert()
- How to append an item to a list using list.append()
- How to add multiple items in a list using list.extend()
- Other ways to extend lists in Python:
- List slicing
- Combining arrays using the + operator
- How to populate an empty list using for loop and append()
- How to populate an empty list using list comprehension
- Append() vs Insert() vs Extend()
- How to Implement a Stack (LIFO)
- What is a stack (LIFO)?
- Coding stacks
- Wrapping up
Методы append() и extend() в Python: добавляем элементы в список
Учимся работать со списками с помощью встроенных функций языка.
Иллюстрация: Катя Павловская для Skillbox Media
Любитель научной фантастики и технологического прогресса. Хорошо сочетает в себе заумного технаря и утончённого гуманитария. Пишет про IT и радуется этому.
Методы append() и extend() позволяют добавить новый элемент в уже существующий список или объединить несколько list-объектов в один. В этой статье мы расскажем и покажем на примерах, как ими пользоваться. А в конце — поделимся менее очевидными способами расширения списков.
Что делает append() в Python
append() добавляет в конец списка элемент, переданный ему в качестве аргумента. Как и все методы в Python, он вызывается через оператор . (точка).
Синтаксис и возвращаемое значение
append() принимает один аргумент item и добавляет его в конец list. Тип параметра может быть любым: числа, строки, словари и так далее. Метод возвращает объект None — то есть ничего.
Примеры использования append()
Допустим, у нас есть список a, который заполнен строками:
Если мы захотим добавить в него новую строку ‘row’, то передадим её в качестве аргумента в append(). Так как метод принадлежит типу list, то вызывать его нужно для объекта a через точку:
a.append('row') print(a) ['car', 'top', 'lot', 'row']
Строка добавилась в конец нашего списка. Всё работает.
Усложним задачу и попробуем добавить ещё один список из двух строк:
b = ['moon', 'sun'] a.append(b) print(a) ['car', 'top', 'lot', 'row', ['moon', 'sun']]
Как мы видим, в a добавился список b с вложенными в него элементами. А если мы захотим, чтобы элементы из b добавились отдельно? Вот так:
К сожалению, с помощью append() этого сделать нельзя, потому что метод принимает только один аргумент. Если вы всё-таки попытаетесь передать несколько объектов через запятую, то интерпретатор вызовет исключение TypeError (ошибка типа):
a = [1, 2, 3] a.append(1, 2, 3) Traceback (most recent call last): File "", line 1, in TypeError: list.append() takes exactly one argument (3 given)
К счастью, есть метод extend(), который позволяет добавить одновременно несколько элементов. О нём и поговорим далее.
Что делает extend() в Python
extend() принимает в качестве параметра итерируемый объект и объединяет его со списком.
Синтаксис и возвращаемое значение
extend() добавляет новые элементы в конец списка, но, в отличие от append(), принимает в качестве параметров итерируемые объекты: списки, кортежи и строки. При этом объединяемые списки могут содержать элементы любых типов: например, вы можете объединить строки с числами или числа с кортежами.
Как и append(), метод возвращает объект None.
Примеры использования extend()
Вернёмся к нашему списку a:
Допустим, мы хотим соединить его с другим списком из строк. Передадим b в extend() и получим результат:
b = ['dog', 'cat'] a.extend(b) print(a) ['car', 'top', 'lot', 'dog', 'cat']
Как видите, каждый элемент из b по отдельности добавился в a.
Мы можем сделать то же самое и с другим итерируемыми объектами — например, кортежами или строками:
c = ('like', 'mode') a.extend(c) print(a) ['car', 'top', 'lot', 'dog', 'cat', 'like', 'mode'] d = 'man' a.extend(d) print(a) ['car', 'top', 'lot', 'dog', 'cat', 'like', 'mode', 'm', 'a', 'n']
Обратите внимание: строки, которые передаются в extend(), превращаются в списки символов и добавляются посимвольно. Так, строка ‘man’ разложилась на ‘m’, ‘a’, ‘n’.
Если передать в extend() не итерируемый объект, например число, Python генерирует TypeError:
a = [1, 2, 3] a.extend(1) Traceback (most recent call last): File "", line 1, in module> TypeError: 'int' object is not iterable
В сообщении нам вежливо объясняют, что число — это не итерируемый объект.
Как ещё можно добавить элементы в список
Чтобы упростить жизнь питонистам, разработчики языка добавили пару фич, которые помогают быстро добавлять элементы в списки.
Оператор +. Он напоминает обычный математический оператор, но со списками действует как функция extend():
a = [2, 3] b = [1, 4] a += b print(a) [2, 3, 1, 4]
Все элементы одного списка добавились в конец другого.
Срезы. Ещё один способ добавить элементы в список — нестандартно использовать индексацию. Выглядит это так:
a = [2, 3] b = [1, 4] a[len(a):] = b print(a) [2, 3, 1, 4]
Выглядит немного странно, но это действительно работает. Когда мы пытаемся обратиться к несуществующим элементам a, язык добавляет новые элементы из списка b, ссылку на который мы передали справа от оператора присваивания.
Что запомнить
- Функция append() позволяет добавлять в список один новый элемент — например, число, строку или другой список.
- Функция extend() работает как append(), но в качестве параметра принимает итерируемый объект: список, кортеж или строку. Содержимое этого объекта поэлементно добавляется в другой список.
- Кроме методов append() и extend() добавить элементы в список можно с помощью оператора + и срезов. Оба способа действуют как extend() — поочерёдно добавляют элементы одного списка в другой.
Больше интересного про код в нашем телеграм-канале. Подписывайтесь!
Читайте также:
Python List .append() – How to Add an Item to a List in Python
Zaira Hira
Lists are one of the most useful and versatile data types available in Python. Lists are a collection of arbitrary objects, just like arrays in other programming languages.
In this tutorial you will learn:
- An overview of lists and how they are defined.
- Methods to insert data in a list using: list.append() , list.extend and list.insert() .
- Syntax, code examples, and output for each data insertion method.
- How to implement a stack using list insertion and deletion methods.
Prerequisites
For this tutorial, you need:
Lists in Python
Lists have the following properties that make them powerful and flexible:
- Lists are ordered.
- Lists are accessed using the index. The first index starts at 0 .
- Lists are mutable and dynamic which means they can be modified after their creation.
How to create a list in Python
You create a list using square brackets in Python.
We can leave them empty and supply values later in the program:
# Create an empty list programming_lang = []
We can also provide values while creating a list:
# Create a filled list programming_lang = ['P','Y','T','H','O','N']
This would create a list as shown in the image below:
How to access items in a list
As list items are ordered, you can access them using their index.
In the image below, «P» is at index «0» whereas «H» is at index «3».
Let’s write a short program to define a list and access its items:
You can also access items using a negative index, where -1 represents the last list item. If we wanted to access the last item from the list above, we could also use index -1 :
How to find the length of a list
We can easily find the length of a list using the len() method.
Methods to Add Items to a List
We can extend a list using any of the below methods:
- list.insert() – inserts a single element anywhere in the list.
- list.append() – always adds items (strings, numbers, lists) at the end of the list.
- list.extend() – adds iterable items (lists, tuples, strings) to the end of the list.
How to insert items in a list with insert()
You can insert items in a list at any index using the insert() method. There are more insertion methods and we will look at them later in this post.
Syntax of insert: insert(index, element) .
Example of insert():
# create a list of odd numbers odd_n = [1,3,5,7,9] # '21' is inserted at index 3 (4th position) odd_n.insert(3, 21) print('List of odd #:', odd_n)
How to append an item to a list using list.append()
We can add a single item at the end of the list using list.append() .
Syntax: list.append(item) .
# crops list crops = ['corn', 'wheat', 'cotton'] # Add 'cane' to the list crops.append('cane') print('Updated crops list: ', crops)
⚠️Note that trying to append more than one item gives an exception, as list.append() takes only a single argument.
How to add multiple items in a list using list.extend()
We can add multiple items to a list using the extend() method.
The below example combines two lists into a single list.
# create a list even_numbers = [2, 4, 8] # create another list more_even_numers = [100, 400] # add all elements of even_numbers to more_even_numbers even_numbers.extend(more_even_numers) print('List after extend():', even_numbers)
Other ways to extend lists in Python:
List slicing
Slicing allows us to select a range of values in a list.
The syntax is shown below:
list[starting index:upto index]
- list[1:3] would return items starting from index 1 up to (not including) index 3.
- Missing left index implies starting from index 0.
- list[:len(list)] means start from index 0 and continue until the end.
- list[0:] implies to start from index 0 until the last item.
Let’s see how we can add lists using slicing.
A = [99, 100, 101] B = [103, 104, 105] # starting from last index +1, add items from list B A[len(A):] = B print('A =', A)
Combining arrays using the + operator
Let’s combine two arrays odd and even into a single list using the + operator.
odd = [1, 3, 5, 7] even = [2, 4, 6, 8] odd += even # odd = odd + even # Output: [1, 2, 3, 4] print('odd and even combined =', odd)
How to populate an empty list using for loop and append()
There are two ways to populate empty lists: using a for loop with append() and using list comprehension.
Let’s first use for loop with append() .
In this example, we are calculating area of a square and appending the result in an array.
# Return area of square # Area of square = length x length def square_area(side_length): result = [] for length in side_length: result.append(length*length) return result lengths = [1, 4, 9, 20] print(square_area(lengths))
We can make the above code efficient by completely skipping the for loop — append() combination and using list comprehension instead. Let’s see how in the next section.
How to populate an empty list using list comprehension
List comprehension makes the code simple and readable by combining the for loop and append() into a single line.
We can modify our previous example to achieve list comprehension. Notice the commented out lines here:
Both of the methods for filling an empty list are valid and suitable in different scenarios.
Append() vs Insert() vs Extend()
Append() always adds a single item at the end of a list. It is useful when only a single item needs to be inserted.
But if you need to make multiple additions, extend() is a better option as it adds iterable items in one batch.
You should use Insert() when insertion is required at a specific index or range of indexes.
How to Implement a Stack (LIFO)
What is a stack (LIFO)?
Stack is an arrangement of items that follows a last-in-first-out order. The item that goes last is the one that comes out first. An example of a stack would be the undo/redo stack in photo editing apps.
The diagram below visually explains a stack.
You can add an item by using append() .
You can remove an item by using pop() . See details of the pop() method here.
Coding stacks
Let’s create a stack class where we first declare an empty list in the init method.
The push() method appends an item to the list.
The pop() method deletes the last item of the list using pop() . If there is no item in the list, an exception will be thrown.
The __ len __ method determines the length of the stack.
Lastly, __ repr __ returns the output in a readable format.
Class definition:
class Stack: def __init__(stack_t): stack_t._items = [] def push(stack_t, item): stack_t._items.append(item) def pop(stack_t): try: return stack_t._items.pop() except IndexError: print("Stack is empty, all items deleted") def __len__(stack_t): return len(stack_t._items) def __repr__(stack_t): return f"stack ()"
Let’s call the class functions and see the output in action.
stack = Stack() # Push items onto the top of the stack stack.push(3) stack.push(5) stack.push(8) stack.push(99) # Print stack print(stack) # Find the length of the stack print("Length of stack is:" ,len(stack)) # Pop items from the stack print("popping last item") stack.pop() print(stack) print("popping last item again") stack.pop() print(stack) print("finally the stack is") print(stack)
We have added 3, 5, 8, 99 to the stack. Next we printed the stack and its length. Afterwards, we popped two items and printed the stack each time.
Wrapping up
In this tutorial, we learned list creation methods. We also looked at some examples along with a practical implementation of stacks to see how it all works.
What’s your favorite thing you learned from this tutorial? Let me know on Twitter!
You can read my other posts here.