In Python, there are several ways to concatenate lists. Here are six methods you can use:
-
Using the
+
Operator:The
+
operator allows you to concatenate two lists together.list1 = [1, 2, 3] list2 = [4, 5, 6] result = list1 + list2 print(result) # Output: [1, 2, 3, 4, 5, 6]
-
Using the
extend()
Method:The
extend
() method appends the elements of one list to the end of another list.list1 = [1, 2, 3] list2 = [4, 5, 6] list1.extend(list2) print(list1) # Output: [1, 2, 3, 4, 5, 6]
-
Using List Comprehension:
You can use list comprehension to combine multiple lists.
list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [7, 8, 9] result = [item for lst in [list1, list2, list3] for item in lst] print(result) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
-
Using the
itertools.chain()
Function:The
itertools.chain()
function allows you to concatenate multiple lists efficiently.from itertools import chain list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [7, 8, 9] result = list(chain(list1, list2, list3)) print(result) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
-
Using the
*
Operator (unpacking):The unpacking operator
*
can be used in a function call to concatenate lists.list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [7, 8, 9] result = [*list1, *list2, *list3] print(result) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
-
Using the list constructor with
sum()
function:You can use the
sum()
function with thelist
constructor to concatenate lists. However, note thatsum()
with a list of lists may not be as efficient as other methods, as it is more suited for numbers.list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [7, 8, 9] result = list(sum([list1, list2, list3], [])) print(result) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
These are some ways to concatenate lists in Python. Choose the method that best suits your needs based on readability, performance, and coding style preferences.