AppDividend
Latest Code Tutorials

How to Add List to List in Python

0

Appending an element to the list is a common operation, but when it comes to adding a list to a list, there are two variations to that. The first is whether you want to add all the elements of a list to another list. The second is whether you want to add the complete list to a list as an element.

In this example, we will see both variations, and according to your requirement, you can use one of them. Let’s see the complete tutorial.

Python add a list to list

To add a list to the list in Python, use the list.extend() method. The extend() is a built-in Python function that adds all the items of an iterable (list, tuple, string, etc.) to the end of the list.

The extend() method takes an iterable as an argument and returns the list.

Syntax

listA.extend(iterable)

Arguments

The extend() method takes an iterable such as list, tuple, string, etc.

Return Value

The extend() method modifies the original list. It doesn’t return any value.

Implementation of adding a list to list

Let’s create two lists using square brackets([ ]).

listA = ["Millie", "Caleb", "Gaten"]

listB = ["Finn", "Noah", "Sadie"]

Now, append the listB to a listA using the extend() function.

listA = ["Millie", "Caleb", "Gaten"]
listB = ["Finn", "Noah", "Sadie"]

listA.extend(listB)
print(listA)

Output

['Millie', 'Caleb', 'Gaten', 'Finn', 'Noah', 'Sadie']

You can see that the listA is modified and added all the elements of the listB.

The list.extend() method does not return a new list; it modifies the existing list.

The extend() method does not add the complete list inside the list. Instead, it adds all the elements of the second list to the first list. It does not add the complete list as an element.

Using list.append() to add a list inside of a list

To add a list inside a list as an element, use the list.append() method. The list append() is a built-in Python function that adds a single element to the existing list.

Syntax

list.append(element)

Arguments

The list.append() function takes a single item and adds it to the end of the list.

Example

Let’s take the above example, and instead of using extend(), let’s use the append() function.

listA = ["Millie", "Caleb", "Gaten"]
listB = ["Finn", "Noah", "Sadie"]

listA.append(listB)
print(listA)

Output

['Millie', 'Caleb', 'Gaten', ['Finn', 'Noah', 'Sadie']]

You can see that it appended a list as an element to the listA.

You can use this approach to add a complete list to a list and not its elements.

That’s it for appending a list to a list tutorial.

See also

Prepend a list in Python

Split a list in Python

Python list multiply

Leave A Reply

Your email address will not be published.

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