Python Append Multiple Items To List
In this article, you will learn how python append multiple items to list using different methods.
Python list is mutable, which means that you can change the list by adding or removing items from it.
You are here to know how to append multiple items to a Python list. Let's see how you can do this.
- Using Extend Method
- Using + operator
- Using slicing method
- Using Intertools Chain
Table Of Contents
1. Append Multiple Items To List Using Extend Method
The extend() method can be used to add multiple items to the list at once.
It can extend items of a list, tuple, string, or another iterable object element by element to the list.
Here is an example:
Look at the above image how all elements of list 'b' are appended to list 'a'.
a = [1, 2, 3]
b = ['a', 'b', 'c']
a.extend(b)
print(a)
The above code will print the following:
[1, 2, 3, 'a', 'b', 'c']
2. Append Multiple Items To List Using + operator
The + operator can be used concatenate two lists or more than two lists to a single list.
You can store the result of the + operator in a variable and use it later.
Look at this example:
You can see in the above image how 2 lists are concatenated and added multiple items to the list.
a = [1, 2, 3]
b = ['a', 'b', 'c']
# add multiple items to list 'a'
a = a + b
print(a)
The above code will print the following:
[1, 2, 3, 'a', 'b', 'c']
3. Append Multiple Items To List Using slicing method
The slicing method can be used to add multiple items between two indexes to the list.
To use this method, you need to take your list and assign values that fit the indexes. example a[start:end] = [item1, item2, item3]
Look at the following example:
Look at the above image to understand how slicing can be used to append multiple items to the list.
# Example 1
a = [1, 2, 3]
b = ['a', 'b', 'c', 'd']
a[1:2] = b
print(a)
Output:
[1, 'a', 'b', 'c', 'd', 3]
# Example 2
a = [1, 2, 3]
b = ['a', 'b', 'c', 'd']
a[2:] = b
print(a)
Output:
[1, 2, 'a', 'b', 'c', 'd']
4. Append Multiple Items To List Using Intertools Chain
The itertools module provides a chain() function that can be used to chain multiple iterables together.
It can be used to add multiple items to the list.
Look at the following example:
Example 1
from itertools import chain
a = [1, 2, 3]
b = ['a', 'b', 'c']
print(list(chain(a, b)))
Output:
[1, 2, 3, 'a', 'b', 'c']
Example 2
from itertools import chain
a = [1, 2, 3]
print(list(chain(a, [4, 5])))
Output:
[1, 2, 3, 4, 5]
Conclusion
In the short guide you have learned how to append multiple items to the list using extend(), + operator, slicing and itertools.chain().