In Python, you can concatenate two lists using the +
operator or the extend()
method.
Here’s an example using the +
operator:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
print(concatenated_list)
In this example, we create two lists list1
and list2
, and then concatenate them using the +
operator to create a new list concatenated_list
.
Alternatively, you can use the extend()
method to append the elements of one list to another:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)
In this example, we use the extend()
method to append the elements of list2
to list1
.
Note that when using the +
operator, a new list object is created, whereas with extend()
the original list is modified in place.
- sunny asked 1 month ago
- You must login to post comments
Your Answer
Please login first to submit.