Introduction
In this tutorial, we will learn different ways to add elements to a list in Python.
There are four ways to add elements to a list in Python.
append(): Add the element to the end of the list.insert(): Inserts the element before the given index.extend(): Expands the list by appending elements from the iterable.- List Concatenation: We can use the + operator to join multiple lists together and create a new list.
Prerequisites
To complete this tutorial, you will need:
- Introduction to installing Python 3. And introduction to coding in Python. How to code in Python 3 series or using VS Code for Python.
Append()
This function adds an element to the end of the list.
fruit_list = ["Apple", "Banana"] print(f'Current Fruits List {fruit_list}') new_fruit = input("Please enter a fruit name:\n") fruit_list.append(new_fruit) print(f'Updated Fruits List {fruit_list}')
Output:
Current Fruits List ['Apple', 'Banana'] Please enter a fruit name: Orange Updated Fruits List ['Apple', 'Banana', 'Orange']
This example added Orange to the end of the list.
insert()
This function adds an element to the given list.
num_list = [1, 2, 3, 4, 5] print(f'Current Numbers List {num_list}') num = int(input("Please enter a number to add to list:\n")) index = int(input(f'Please enter the index between 0 and {len(num_list) - 1} to add the number:\n')) num_list.insert(index, num) print(f'Updated Numbers List {num_list}')
Output:
Current Numbers List [1, 2, 3, 4, 5] Please enter a number to add to list: 20 Please enter the index between 0 and 4 to add the number: 2 Updated Numbers List [1, 2, 20, 3, 4, 5]
This example adds 20 at index 2. 20 is included in the list at this index.
Extend()
This function adds iterable elements to the list.
extend_list = [] extend_list.extend([1, 2]) # extending list elements print(extend_list) extend_list.extend((3, 4)) # extending tuple elements print(extend_list) extend_list.extend("ABC") # extending string elements print(extend_list)
Output:
[1, 2] [1, 2, 3, 4] [1, 2, 3, 4, 'A', 'B', 'C']
This example added a list of [1, 2]. Then added a number (3, 4). And then added a string ABC.
List addition
If you need to concatenate multiple lists, you can use the + operator. This creates a new list and the original lists remain unchanged.
evens = [2, 4, 6] odds = [1, 3, 5] nums = odds + evens print(nums) # [1, 3, 5, 2, 4, 6]
This example appends the list of pairs to the end of the list of odds. The new list will contain the elements from the list from left to right. This is similar to string concatenation in Python.
Result
Python provides several ways to add elements to a list. We can add an element at the end of a list and insert an element at a given index. We can also add a list to another list. If you want to concatenate multiple lists, use the overloaded + operator.