What is the difference between the append() and extend() methods in Python?
Long Answer
Views 194
Answer:
The append()
and extend()
methods are used to add elements to a list in Python, but they behave differently.
The append()
method adds a single item to the end of the list:
list1 = [1, 2, 3] list1.append(4) print(list1) # Output: # [1, 2, 3, 4]
The extend()
method, on the other hand, adds multiple elements to the end of the list, by extending the list with another list:
list1 = [1, 2, 3] list2 = [4, 5, 6] list1.extend(list2) print(list1) # Output: # [1, 2, 3, 4, 5, 6]
So, in summary:
-
append()
adds a single item to the end of the list. -
extend()
adds multiple items to the end of the list, by extending the list with another list.
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Python, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.