How to append one list to another in Python

Lists are fundamental data structures for storing collections of items. When you have multiple lists containing related data, you may want to consolidate them into a single list. Appending one list to another allows programmers to gather all the related data in a single list. This can make it easier to manage and work with the data as a cohesive unit. Working with a single comprehensive list of data points might be useful in data processing, visualization, and statistical analysis. Fortunately, many built-in methods exist to append one list to another in Python.

Following are examples of appending lists together.

Problem 1: Append one list to another list

For Example:
Input List 1 = [63, 52, 21]
Input List 2 = [61, 76, 92, 43]

Output=[63, 52, 21, 61, 76, 92, 43]

Problem 2: Append one list as an element into the another list

For Example:
Input Lit 1 = [63, 52, 21]
Input List 2 = [61, 76, 92, 43]

Output=[63, 52, 21, [61, 76, 92, 43]]

Using list.extend() to Combine two lists

The extend() method is one of the easiest and the most straightforward method to append one list to another. However, extend() modifies an original list by adding all the elements from a new list to the end of the original list. Here is how to use this simple method

#Python code method 1
list1 = [5, 6, 8]

list2 = [45, 5, 7]

list1.extend(list2)

print(list1)
# code ends here
Output:

[5, 6, 8, 45, 5, 7]

In this code snippet, list2 is appended to list 1 using the extend() method. After the operation, list1 will have all the elements of list2. However, the extend() method modifies the original list and does not return a new list. Therefore, if you want to keep an original list intact, consider using other methods like concatenation (+ operator) or slicing with += operator.

Using list.append to append one list to another in python

We can use the append() method to append one list to another in Python. This method adds a new list as a single element to an original list thus creating a nested list.

Here is how you can use the append() method.

#Python code method 2

list_1 = [1, 2, 3, 4]

list_2 = [5, 6, 7, 8]

list_1.append(list_2)

print(list1)

#code ends here
Output:

[1, 2, 3, 4, [5, 6, 7, 8]]

However, it’s important to exercise caution when using this method because it adds a new list as a single element to the original list. Consequently, this results in a nested list, which is not necessary for many practical purposes. If you want to avoid creating a nested list, consider using the extend() method to append lists to each other.

Using the chain function in the itertools module to append one list to another list

The itertools.chain() function is not primarily used to append two lists. Instead, it is used to append multiple iterable objects (lists, sets, tuples) into one sequence. It creates an iterator that iterates over each input iterable, effectively chaining them together. We can also use itertools.chain() function to combine multiple lists into a single iterable.

Here’s how you can do this in python.

#Python code method 3
import itertools

list_1 = [1, 2, 3, 4]

list_2 = [5, 6, 7, 8]

list_3 = [9, 10, 11, 12]

list_all = list(itertools.chain(list_1, list_2, list_3))

print(list_all)
#code ends here
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

In the above code snippet, itertools.chain() function combined multiple lists into a single iterable sequence. Upon combining all the iterables into a single sequence, we need to convert them into list by wrapping the itertools.chain() function inside the list() function.

It’s important to note that the itertools.chain function doesn’t directly append one list to another. Instead, it creates an iterable sequence containing elements from all the iterables that are chained together. Unlike the append() method, which can lead to nested lists, itertools.chain() avoids unnecessary nesting, making it an efficient way to merge lists while maintaining a flat structure. This can be particularly useful for tasks involving multiple data sources or iterating through various collections.

using for loop for Appending a list to another list

The simplest approach is to use for loop to append one list element to another. It involves iterating through the elements of a new list and sequentially appending each element to an original list one by one. Lets understand through example:

#Python code method 4

list_1 =  [1, 2, 3, 4]

list_2 = [5, 6, 7, 8]

for item in list_2:

    list_1.append(item)
    
print(list1)

#code ends here
Output:
[1, 2, 3, 4, 5, 6, 7, 8]

In the above code snippet, the for loop iterates through each element of list_2 and append it to the list_1 using the append() method. Once the loop executes, list_1 will contain all the elements of list_2.

Using the Concatenation + Operator for appending

In Python, two lists can be concatenated with the + operator. The + operator creates a new list creating the new list with elements from an original list and the new list.

For instance, consider a scenario where you’re managing a store’s inventory with two lists: one for available products and another for products on sale. You can use the + operator to merge these lists into a comprehensive collection of products, encompassing both regular-priced and discounted items.

Here’s how to combine these lists using the concatenation operator (+):

#Python code method 5

# Lists representing available products and products on sale
available_products = ["Laptop", "Smartphone", "Tablet", "Printer", "Monitor", "Keyboard"]
products_on_sale = ["Smart TV", "Headphones", "Tablet", "Bluetooth Speaker"]

# Combining the lists using the + operator
all_products = available_products + products_on_sale

print("Available Products:", available_products)
print("Products on Sale:", products_on_sale)
print("All Products:", all_products)

# code ends here
Output:
Available Products: ['Laptop', 'Smartphone', 'Tablet', 'Printer', 'Monitor', 'Keyboard']
Products on Sale: ['Smart TV', 'Headphones', 'Tablet', 'Bluetooth Speaker']
All Products: ['Laptop', 'Smartphone', 'Tablet', 'Printer', 'Monitor', 'Keyboard', 'Smart TV', 'Headphones', 'Tablet', 'Bluetooth Speaker']

In the above code snippet, the + operator combines the two lists elements into a new list `all_products`. On top of that, original lists i.e., available_products and products_on_sale remains unchanged.

It is worth mentioning here that the concatenation + operator does not modify an original list. Instead, it creates a new list. Therefore, if you want to append elements to one of the original lists directly, this method is unsuitable.

However, you can use a plus-equals operator (+=) to concatenate all the elements into available_products list. The += operator acts as an in-place addition operator and can be used for string concatenation when you want to combine multiple strings together into one.

Here is how you can append the above two lists using += operator.

# Lists representing available products and products on sale
available_products = ["Laptop", "Smartphone", "Tablet", "Printer", "Monitor", "Keyboard"]
products_on_sale = ["Smart TV", "Headphones", "Tablet", "Bluetooth Speaker"]

# Combining the lists using the + operator
available_products += products_on_sale

print("Available Products:", available_products)

Output:

Available Products: ['Laptop', 'Smartphone', 'Tablet', 'Printer', 'Monitor', 'Keyboard', 'Smart TV', 'Headphones', 'Tablet', 'Bluetooth Speaker']

using the slicing operator to append one list to another

The slicing operator in Python is a useful tool for appending elements from one list to another. Slicing allows you to combine lists without adding nested structures. It takes components from a source list and concatenate them onto the end of the destination list. This method keeps the lists’ original structure while improving code readability.

Here’s an example that illustrates using the slicing operator to append elements from one list to another:

# Initial lists
list_1 = [2, 4, 6, 8]
list_2 = [1, 3, 5, 7]

# Using slicing to append elements from list_2 to list_1
list_1[len(list_1):] = list_2

# Print the combined list
print(list_1)

Output:

[2, 4, 6, 8, 1, 3, 5, 7]

In the above code example, list_2 is appended to list_1 using slicing and the += operator. The slicing operation list_1[len(list_1):] targets the position where the list_1 ends, effectively appending list_2 to it.

Just like the extend() method and the += operator, this method also alters the original list. Consequently, if you wish to preserve the integrity of the original list, it’s advisable to opt for alternatives such as the concatenation operator + or other methods that have been covered in this article.

Conclusion

Python offers multiple built-in methods to effectively append lists, thus enabling smoother data handling and manipulation. The discussed techniques provide versatility when it comes to combining lists. From the direct extend() method, which augments an original list by adding elements from a new list, to the append() method that introduces nested lists, Python provides options catering to diverse needs. The advanced itertools.chain() function offers a streamlined approach to chaining multiple iterables together, maintaining a flat structure for efficient data merging. Additionally, the + operator creates a new list by concatenating elements, offering a straightforward way to combine two lists. The slicing operator, on the other hand, ensures a seamless merge while maintaining the original structure of lists, enhancing code clarity. These methods collectively empower programmers to tailor their approach based on specific requirements, ensuring an efficient and concise manner of appending lists in Python.

If you find this article helpful and have any further queries, please let us know. Contact us.

Leave a Comment

Your email address will not be published. Required fields are marked *