How to append list to another list in Python?

Python – Append list to another list using 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 of 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.

Examples

1. Append a list to another list

In the following example, we create two lists: list1 and list2, and append the second list list2 to the first one list1.

Python Program

# Take two lists
list1 = [6, 52, 74, 62]
list2 = [85, 17, 81, 92]

# Extend first list with the second one
list1.extend(list2)

# Print the first list
print(list1)
Run Code Copy

Output

[6, 52, 74, 62, 85, 17, 81, 92]

The contents of the list1 are modified.

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

# Take two lists
list1 = [6, 52, 74, 62]
list2 = [85, 17, 81, 92]

# Make of copy of list1
result = list1.copy()

# Append the second list to first list
result.extend(list2)

# Print the first list
print(result)
Run Code Copy

Output

[6, 52, 74, 62, 85, 17, 81, 92]

list1 is preserved while the resulting extended list is in result.

3: Append a list to another list using 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

# Take two 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 first list
print(list1)
Run Code Copy

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

Code copied to clipboard successfully 👍