This tutorial guides you on the difference between Python’s list methods append() and extend() methods.
Difference between Python’s list methods append and extend
Both the methods are defined for Mutable Sequence Types. Here is the list of operations defined on mutable sequence types. Let’s try to learn the exact difference between these two operations with examples below.
It appends the sequence seq2 to the end of the sequence seq1. Therefore, it results in a nested list and it does not look like a flatten list.
>>> x = [10,20,30] >>> x.append([11,22]) >>> x [10, 20, 30, [11, 22]]
It extends the sequence seq1 with the contents of sequence seq2. Therefore, the resulted list looks like a flatten list.
We can say that the above syntax is equivalent to:
seq1 += seq2
>>> y = [10,20,30] >>> y.extend([11,22]) >>> y [10, 20, 30, 11, 22]
Difference between list’s append() and extend() methods
From the above examples, it is understood that append() adds the list object to the end of the list. Therefore, the length of the list increase by 1.
And in case of extend(), it iterates the list elements passed as an argument and add each element to the list. Therefore it results in extending the list and the length of the list increase by the number of elements that were iterated/ iterable in the argument.
That’s it. You had learnt the difference between list’s append and extend methods with examples.
You’ll also like:
- Convert list of lists to flat list – flatten list in Python ?
- String Formatting in Python – Examples
- Single digit number to double digits string conversion in Python
- String Immutability with Examples in Python
- Python Program to Check Given Number is Odd or Even
- Increase the cell width of the Jupyter Notebook in browser
- Add python3 kernel to jupyter IPython notebook ?
- Programs to Print Patterns – Pyramid, Triangle using Star
- How to change the default theme in Jupyter Notebook ?
- Change the Jupyter Notebook startup folder in Windows & Mac
- To run Jupyter Notebook on Windows from command line
- String Slicing in Python with Examples
- Python program to find the greatest of three numbers
- Concatenate or join two lists using Python ?
- String indexing in Python with Examples
- How to check if the given list is empty in Python ?
- Remove non-numeric characters from string in Python
- Install Python 3 on Windows 10 machine
- Convert negative to positive number in Python
- Create list of lists in Python
- Extract numbers from a string in python
- How to access index and value in for loop – Python?
- Find index of an element in a list – Python