concatenate two lists in Python?

We can concatenate two lists in Python using the +operator or the extend() method.

1. Using the + operator:

This creates a new list by joining two lists together.

a = [1, 2, 3]
b = [4, 5, 6]
res = a + b
print(res)

Output

[1, 2, 3, 4, 5, 6]

2. Using the extend() method:

This adds all the elements of the second list to the first list in-place.

a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
print(a)

Output

[1, 2, 3, 4, 5, 6]

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *