How to Append List to List in Python

Here are two ways to append a list to a list in Python:

  1. Using list.extend()
  2. Using list.append()

Method 1: Using list.extend()

The extend() method adds each element of the second list to the end of the first list. The method modifies the list in place. This means the original list will be changed.

The size of the list will be increased by a number of elements in its argument.

Visual representation

Visual representation of list.extend() method

Example

# Define two lists
list1 = [11, 21, 19]
list2 = [46, 18, 30]

# Append list2 to list1
list1.extend(list2)

print(list1)

Output

 [11, 21, 19, 46, 18, 30]

Method 2: Using list.append()

The append() method will add the entire list as a single element to the end of the first list. This means that the second list will be nested within the first list.

Visual representation

Visual representation of using list.append() method

Example

# Define two lists
list1 = [11, 21, 19]
list2 = [46, 18, 30]

# Append list2 as a single element to list1
list1.append(list2)

print(list1)

Output

[11, 21, 19, [46, 18, 30]]

After using append(), list2 is added as a single element, meaning it’s nested within list1. Any changes made to list2 will be reflected in list1 since the list is appended by reference.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.