You can concatenate two lists in Python using the addition operator (+
). This operator combines the elements of both lists into a new list, preserving the order of elements.
Here's a simple example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
print(concatenated_list) # Output: [1, 2, 3, 4, 5, 6]
Practical Insights:
- Concatenation creates a new list: The original lists remain unchanged.
- Order matters: The order of elements in the resulting list follows the order of the original lists.
- Data types: Both lists must contain the same data type or compatible data types for concatenation to work.
Alternative Methods:
extend()
method: Theextend()
method modifies the original list by adding elements from another list to the end.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
- List comprehension: You can use list comprehension to create a new list containing elements from both original lists.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = [element for sublist in [list1, list2] for element in sublist]
print(concatenated_list) # Output: [1, 2, 3, 4, 5, 6]
Choosing the Right Method:
- Use the
+
operator for creating a new list without modifying the original lists. - Use the
extend()
method when you want to modify the original list. - Use list comprehension for a more concise and efficient way to concatenate lists, especially when dealing with nested lists.