Difference between append() and extend() functions in Python List
Here we will learn about the basic difference between append() and extend() function in Python list. Lists are one of the most important features of data structures used in python or any other higher-level languages. Appending and Extending are the two ways of adding new elements into the list. Let us go through them in brief.
Append(): This function adds an element at the extreme end of the given list. The entering element can be of any data type as a string, an integer, a boolean, or even another list.
The syntax of this function is : a.append(x)
Let us take an example through a code:
c = [1, 2, 3] c.append('4') print(c)
The output will be : [1,2,3,4]
Here the length of the list has increased by one element because only one element is added to the list. We can also add another list at the end of one list.
c = [1, 2, 3, 4] c.append([5, 6, 7]) print(c)
The output will look like: [1, 2, 3, 4, [5, 6, 7]]
Extend function(): This function adds the iterable objects to a list one by one. The final list will contain all the elements of both lists. An iterable object includes an object that we can iterate through lists, tuples or strings.
Let us look at an example of extending another list to a list.
c = [1, 2, 3, 4] c.extend([5, 6, 7]) print(c)
The output will be : [1, 2, 3, 4, 5, 6, 7]
*Here in this output we can see that the length of the list grew thrice, which is unlike to append function. This shows the basic difference between them.
Hence the conclusion is appending function adds only one object of any type to a list. Whereas extending function operates on iterable objects and appends every item to the list.