Python List Methods with Examples

List is one of the Python built-in data types that acts as a container for various items. Items can be string, int, float, boolean, nested list, set, and other data types.

Python List is a mutable data type means after initializing it, we can change its items further also. But, we cannot change the items in int, decimal, bool, string, tuple, and range once they are initialized as they are all immutable data types.

Due to this mutable type, a list is a dynamic container that is used mostly while programming to store items.

There are altogether 11 methods available, that list supports till now and we will discuss each of them thoroughly with examples.

Python List Methods with Examples

How to check all the methods available in the list?

⇒ To check all the methods available, simply use list comprehension as:

>>> [method for method in dir(list) if not method.startswith("__")]
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>>

Let’s take a variable named my_list containing 4 items initially. We will perform all the list methods in that variable.

my_list = ["Python", "Java", "C", "R"]

1. append( )

This method is used to append a new item at the end of the list.

>>> my_list = ["Python", "Java", "C", "R"]
>>> my_list.append("JavaScript")
>>> my_list
['Python', 'Java', 'C', 'R', 'JavaScript']
>>> my_list.append("Swift")
>>> my_list
['Python', 'Java', 'C', 'R', 'JavaScript', 'Swift']
>>>

append( ) is equivalent to my_list[len(my_list):] = <any_item>

>>> my_list[len(my_list):] = ["Go"]
>>> my_list
['Python', 'Java', 'C', 'R', 'JavaScript', 'Swift', 'Go']
>>>

2. clear( )

This method removes all items from the list.

>>> my_list.clear()
>>> my_list
[]

To delete list object my_list entirely, you have to use the del keyword.

>>> my_list = ["Python", "Java", "C", "R"]
>>> del my_list
>>> my_list
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'my_list' is not defined

3. copy( )

This method returns a shallow copy of the list.

>>> my_list = ["Python", "Java", "C", "R"]
>>> my_list_1 = my_list.copy()
>>> my_list_1
['Python', 'Java', 'C', 'R']
>>> my_list_2 = my_list_1[:]
>>> my_list_2
['Python', 'Java', 'C', 'R']
>>>

Note: we can also use my_list[:] instead of my_list.copy()

4. count( )

This method returns the count of the particular item occurring in the list.

Let’s append the “Python” item three times in my_list and then count its occurrence.

>>> my_list = ["Python", "Java", "C", "R"]
>>> my_list.append("Python")
>>> my_list.append("Python")
>>> my_list.append("Python")
>>> my_list
['Python', 'Java', 'C', 'R', 'Python', 'Python', 'Python']
>>> my_list.count("Python")
4
>>>

5. extend( )

This method extends the list by appending elements from the iterable. Iterable is an object(containers for data) that you can iterate over with the help of a for loop.

>>> my_list = ["Python", "Java", "C", "R"]
>>> list1 = [1, 2, 3]
>>> my_list.extend(list1)
>>> my_list
['Python', 'Java', 'C', 'R', 1, 2, 3]
>>> str1 = "Coder"
>>> my_list.extend(str1)
>>> my_list
['Python', 'Java', 'C', 'R', 1, 2, 3, 'C', 'o', 'd', 'e', 'r']
>>> tuple1 = (4, 5, 6)
>>> my_list.extend(tuple1)
>>> my_list
['Python', 'Java', 'C', 'R', 1, 2, 3, 'C', 'o', 'd', 'e', 'r', 4, 5, 6]
>>> 

Note: data types like list, tuple, and string are all iterable objects where for loop can be used. extend( ) method is also equivalent to my_list[len(my_list):] = <any_iterable>

6. index( )

This method returns the index value of the item that passes as an argument.

>>> my_list = ["Python", "Java", "C", "R"]
>>> my_list.index("Python")
0
>>> my_list.index("R")
3

It raises ValueError if the item is not present in the list.

>>> my_list.index("Swift")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'Swift' is not in list

7. insert ( )

This method inserts the new item at a given position. It requires passing two arguments: index position and value.

>>> my_list = ["Python", "Java", "C", "R"]
>>> my_list.insert(0, "Swift")
>>> my_list
['Swift', 'Python', 'Java', 'C', 'R']
>>> my_list.insert(9, "Go")
>>> my_list
['Swift', 'Python', 'Java', 'C', 'R', 'Go']

Note: For any index value provided above the length of the list, the new item will be appended at the end of the list as like append( ).

8. pop( )

This method removes and returns the last item by default if no index position is passed as an argument.

>>> my_list = ["Python", "Java", "C", "R"]
>>> my_list.pop()
'R'
>>> my_list.pop(1)
'Java'
>>> my_list
['Python', 'C']

It raises IndexError if the list is empty or the index is out of range.

>>> # returns error as my_list has length of 4
>>> my_list.pop(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range
>>>

9. remove( )

It removes the first occurrence of value i.e if two same items are located at the first and last position, the first item will be removed prior to the last item.

>>> my_list = ["Python", "Java", "C", "R"]
>>> my_list.insert(2, "Python")
>>> my_list
['Python', 'Java', 'Python', 'C', 'R']
>>> my_list.remove("Python")
>>> my_list
['Java', 'Python', 'C', 'R']
>>>

It raises ValueError if the value is not present in the list.

>>> my_list.remove(".Net")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>>

10. reverse( )

It reverses the list items i.e. first and second items will be the last and second last items after this method is applied.

>>> my_list = ["Python", "Java", "C", "R"]
>>> my_list.reverse()
>>> my_list
['R', 'C', 'Java', 'Python']
>>>

11. sort( )

This method sorts the list in ascending order and returns None.

>>> my_list = ["Python", "Java", "C", "R"]
>>> my_list.sort()
>>> my_list
['C', 'Java', 'Python', 'R']
>>>

To sort the list in descending order, pass them reverse=True as an argument.

>>> my_list = ["Python", "Java", "C", "R"]
>>> my_list.sort(reverse=True)
>>> my_list
['R', 'Python', 'Java', 'C']
>>>

If you want to apply your own sorting mechanism, then define your function and pass the key=<function>  as an argument.

Let’s sort those items in the list according to their length.

First, define a function

>>> def return_length(item):
...     return len(item)
...

Then call that function as:

>>> my_list = ["Python", "Java", "C", "R", "Swift", "Go"]
>>> my_list.sort(key=return_length)
>>> my_list
['C', 'R', 'Go', 'Java', 'Swift', 'Python']
>>> # in reverse order
>>> my_list.sort(key=return_length, reverse=True)
>>> my_list
['Python', 'Swift', 'Java', 'Go', 'C', 'R']
>>>

Reference: Python Official doc

Leave a Comment