![]() |
VOOZH | about |
Our task is to merge multiple lists into a single list by appending all their elements. For example, if the input is a = [1, 2], b = [3, 4], and c = [5, 6], the output should be [1, 2, 3, 4, 5, 6].
itertools.chain() function from the itertools module is another way to combine lists efficiently. It creates an iterator that combines multiple lists.
[1, 2, 3, 4, 5, 6]
Explanation:
Other methods that we can use to append multiple lists at once are:
Table of Content
One of the easiest ways to append multiple lists is by using the extend() method as this method allows us to add elements from one list to another list. ( Note: It modifies the original list in place.)
[1, 2, 3, 4, 5, 6]
Explanation: Here we extend list a by adding elements of list b and then list c.
Another simple way to append multiple lists is by using the + operator. It creates a new list by concatenating the lists.
[1, 2, 3, 4, 5, 6]
Explanation: a + b + c concatenates all three lists into a single list, the result is stored in res and printed as [1, 2, 3, 4, 5, 6].
We can also use list comprehension to append multiple lists in a very Pythonic way. It gives us full control over how we combine the lists.
[1, 2, 3, 4, 5, 6]
Explanation:
This method is a bit more advanced but can be useful in specific cases. We can use the zip() function to group elements from multiple lists to combine them into a single list.
[1, 3, 5, 2, 4, 6]
Explanation:
zip(a, b, c) groups elements from a, b, and c into tuples like (1, 3, 5), (2, 4, 6).[item for sublist in zip(a, b, c) for item in sublist] flattens these tuples into a single list, resulting in [1, 3, 5, 2, 4, 6].append() method can also be used in a loop to add elements from multiple lists to an empty list. This method is slower than others because it adds one element at a time.
[1, 2, 3, 4, 5, 6]