How To Combine Multiple Lists Into One List Python (original) (raw)
Last Updated : 14 Feb, 2024
Combining multiple lists into a single list is a common operation in Python, and there are various approaches to achieve this task. In this article, we will see how to combine multiple lists into one list in Python.
Combine Multiple Lists Into One List Python
Below are some of the ways by which we can see how we can combine multiple lists into one list in Python:
Combine Multiple Lists Using the '+' operator
In this example, the `+` operator concatenates three lists (`number`, `string`, and `boolean`) into a new list named `new_list`. The resulting list contains elements from all three original lists, showcasing a concise way to combine multiple lists in Python.
Python3 `
number = [1, 2, 3] string = ['a', 'b', 'c'] boolean = [True, False]
new_list = number + string + boolean print(new_list)
`
Output
[1, 2, 3, 'a', 'b', 'c', True, False]
Combine Multiple Lists Using extend() method
In this example, the `extend()` method is used to append elements from `extra_set_1` and `extra_set_2` to the `main_set`. The final `main_set` contains all elements from the original set and the additional elements from the two extra sets, demonstrating an effective way to merge multiple lists in Python.
Python3 `
main_set = [1, 2, 3] extra_set_1 = [4, 5, 6] extra_set_2 = [7, 8, 9]
main_set.extend(extra_set_1) main_set.extend(extra_set_2)
print(main_set)
`
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Combine Multiple Lists Using for loop
In this example, a loop iterates through a list of lists (`lists`), and the `extend()` method is used to append elements from each inner list to the `organized_list`. The final `organized_list` represents the flattened version of the original nested lists, illustrating a method to merge sublists into a single list in Python.
Python3 `
lists = [[1, 2, 3], ['a', 'b', 'c'], [True, False]] organized_list = []
for inner_list in lists: organized_list.extend(inner_list)
print(organized_list)
`
Output
[1, 2, 3, 'a', 'b', 'c', True, False]
Combine Multiple Lists Using itertools.chain()
Method
In this example, the `itertools.chain()` function is employed to efficiently combine three lists (`list1`, `list2`, and `a`) into a single list named `combined_list`. The resulting list contains elements from all three original lists, showcasing a concise and memory-efficient way to merge multiple lists in Python.
Python3 `
from itertools import chain
list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] a = ['True', 'False', 'True'] combined_list = list(chain(list1, list2,a))
print(combined_list)
`
Output
[1, 2, 3, 'a', 'b', 'c', 'True', 'False', 'True']