Contents
Python – Append List to Another List – extend()
To append a list to another list, use extend() function on the list you want to extend and pass the other list as argument to extend() function.
In this tutorial, we shall learn the syntax of extend() function and how to use this function to append a list to other list.
Syntax – extend()
Following is the syntax of extend() function.
list1.extend(list2)
where elements of list2 are appended to the elements of list1.
extend() does inplace update to the original list list1
. The function returns None
.
Example 1: Append a list to another list
In the following example, we will create two lists and append the second list to the first one.
Python Program
#initialize lists
list1 = [6, 52, 74, 62]
list2 = [85, 17, 81, 92]
#extend first list with the second one
list1.extend(list2)
#print the extended list
print(list1)
Run Output
[6, 52, 74, 62, 85, 17, 81, 92]
The contents of the list1
are modified.
Example 2: Append a list to another list keeping a copy of original list
If you would like to keep the contents of original list unchanged, copy the list to a variable and then add the other list to it.
Python Program
#initialize lists
list1 = [6, 52, 74, 62]
list2 = [85, 17, 81, 92]
#make of copy of list1
result = list1.copy()
#append the second list
result.extend(list2)
#print resulting list
print(result)
Run Output
[6, 52, 74, 62, 85, 17, 81, 92]
list1
is preserved while the resulting extended list is in result
.
Example 3: Append a list to another list – For Loop
You can also use a For Loop to iterate over the elements of second list, and append each of these elements to the first list using list.append() function.
Python Program
#initialize lists
list1 = [6, 52, 74, 62]
list2 = [85, 17, 81, 92]
#append each item of list2 to list1
for item in list2:
list1.append(item)
#print the extended list
print(list1)
Run Output
[6, 52, 74, 62, 85, 17, 81, 92]
Summary
In this tutorial of Python Examples, we learned how to extend a list with another list appended to it, with the help of well detailed example programs.
Related Tutorials
- How to Check if Python List is Empty?
- Python Program to Find Smallest Number in List
- Shuffle Python List
- Python – How to Create an Empty List?
- Python Program to Find Largest Number in a List
- Python Program to Find Unique Items of a List
- Python List of Functions
- Python – Check if Element is in List
- How to Get List of all Files in Directory and Sub-directories?
- Python – Check if List Contains all Elements of Another List