To concatenate lists in Python, you can use the +
operator or the extend()
method. Here’s how you can use each method:
- Using the
+
operator: You can concatenate two or more lists using the+
operator. Here’s an example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
print(concatenated_list) # Output: [1, 2, 3, 4, 5, 6]
In this example, we concatenate list1
and list2
using the +
operator, resulting in a new list concatenated_list
that contains the elements of both lists.
Note: The +
operator creates a new list as the result of concatenation. If you want to modify one of the existing lists, you should use the extend()
method.
- Using the
extend()
method: Theextend()
method allows you to append elements from another list or iterable to an existing list. Here’s an example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
In this example, we use the extend()
method on list1
to append the elements of list2
to it. The extend()
method modifies the original list list1
in place.
You can use either method based on your specific needs. If you want to create a new list that contains the concatenated elements of two or more lists, use the +
operator. If you want to modify an existing list by appending elements from another list, use the extend()
method.
+ There are no comments
Add yours