What is the difference between append() and extend() methods in Python lists? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is the difference between append() and extend() methods in Python lists?

Explain how to use both where to use bith

17th Aug 2023, 5:01 PM
Zahed Shaikh
Zahed Shaikh - avatar
2 Answers
+ 3
Both `append()` and `extend()` are methods used with Python lists, but they have difference - The `append()` method is used to add a single element to the end of a list. For example: ```python my_list = [1, 2, 3] my_list.append(4) # Now my_list is [1, 2, 3, 4] ``` - The `extend()` method is used to add multiple elements (from another iterable, like a list or tuple) to the end of a list. For example: ```python my_list = [1, 2, 3] my_list.extend([4, 5, 6]) # Now my_list is [1, 2, 3, 4, 5, 6] ``` Remember, `append()` adds a single element, while `extend()` adds multiple elements from an iterable.
17th Aug 2023, 5:06 PM
Zahed Shaikh
Zahed Shaikh - avatar
+ 3
Zahed Shaikh , list.append(element) - adds an element at the end of the list. list.extend(list2) - adds each element of a specified list(list2)[CAN BE ANY TYPES, SUCH AS TUPLES OR SETS] at the end of the list. Example: x = [1,2,3] x.append(4) #x = [1,2,3,4] mylist = [4,5,6] y = [7,8,9] mylist.extend(y) #mylist = [4,5,6,7,8,9]
17th Aug 2023, 5:10 PM
Dragon RB
Dragon RB - avatar