How to use extend() method of List in Python?

 The extend() method adds all the elements of an iterable (list, tuple, string etc.) to the end of the list.

For example, the following code extends list1 with iterable - list2/set2.

list1 = [1, 2, 3]
list2 = [4, 5]

list1.extend(list2)
print(list1)

# Output
[1,2,3,4,5]

list1 = [1, 2, 3]
set2 = (4, 5)

list1.extend(set2)
print(list1)

# Output
[1,2,3,4,5]
This is the same behavior as += for list if you have been using it.

list1 = [1, 2, 3]
list2 = [4, 5]

list1 += list2
print(list1)

# Output
[1,2,3,4,5]
Compared to append(), extend() adds all elements of an iterable as separate elements to the list while append() simply appends iterable as an element.

list1 = [1, 2, 3]
list2 = [4, 5]

list1.append(list2)
print(list1)

# Output
[1, 2, 3, [4, 5]]

No comments:

Post a Comment