Today's Featured Video:



Combining Two Lists in Python

Learn how to combine two lists in Python using various methods, including concatenation, adding elements, and merging lists of different lengths. …


Updated May 6, 2023

Learn how to combine two lists in Python using various methods, including concatenation, adding elements, and merging lists of different lengths.

What is a List in Python?

In Python, a list is a collection of items that can be of any data type, including strings, integers, floats, and other lists. Lists are defined by enclosing the elements in square brackets []. For example:

my_list = [1, 2, 3, "hello", 4.5]

Why Combine Two Lists?

You may need to combine two lists for various reasons, such as:

  • Merging data from different sources
  • Creating a single list from multiple input values
  • Performing operations on combined data

Method 1: Concatenation using + Operator

One way to combine two lists is by using the + operator. This method concatenates (joins) the elements of both lists into a new list.

list1 = [1, 2, 3]
list2 = [4, 5, 6]

combined_list = list1 + list2

print(combined_list)

Output: [1, 2, 3, 4, 5, 6]

Method 2: Using extend() Method

Another way to combine two lists is by using the extend() method. This method adds all elements from one list to another.

list1 = [1, 2, 3]
list2 = [4, 5, 6]

list1.extend(list2)

print(list1)

Output: [1, 2, 3, 4, 5, 6]

Method 3: Using + Operator with Multiple Lists

You can also combine multiple lists using the + operator. Simply add each list one by one.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = ["a", "b", "c"]

combined_list = list1 + list2 + list3

print(combined_list)

Output: [1, 2, 3, 4, 5, 6, 'a', 'b', 'c']

Method 4: Using itertools.chain() Function

If you have lists of different lengths and want to combine them into a single list, you can use the chain() function from the itertools module.

import itertools

list1 = [1, 2, 3]
list2 = [4, 5]

combined_list = list(itertools.chain(list1, list2))

print(combined_list)

Output: [1, 2, 3, 4, 5]

Conclusion

Combining two lists in Python can be achieved using various methods, including concatenation, adding elements, and merging lists of different lengths. Whether you’re a beginner or an experienced programmer, these methods will help you create a single list from multiple input values.

By following the step-by-step explanations and code snippets provided in this article, you’ll be able to combine two lists in Python like a pro!

Stay up to date on the latest in Python, AI, and Data Science

Intuit Mailchimp