Python List Methods: All you need to Know

Posted in /  

Python List Methods: All you need to Know
vinaykhatri

Vinay Khatri
Last updated on December 30, 2024

    The list is one of Python's built-in data structures. It is a mutable and ordered data structure that is similar to arrays of other Programming languages. We can use a Python list object to store multiple items in sequential order with a single variable name. As a list is an in-built data structure, it comes with some built-in functions(which are known as list methods). To use the list method, we write the list name followed by the dot operator and method call.

    This Python tutorial will discuss all the methods available for a Python list object, with examples. So let's get started with a brief introduction to the Python list itself.

    Python List overview

    A Python list can store multiple items of different data types, and it stores all items in an ordered way. The data values stored within a list are known as list items, and sometimes they are also referred to as list elements. To initialize a list, we can either use the list() function or square bracket, which Python developers generally use.

    Example (Initialize List)

    #list with square bracket
    programming = ["Python","JavaScript", "Java", "C++",]

    Or

    #list with list Function
    programming = list(("Python","JavaScript", "Java", "C++"))

    List map every item to a unique index value that starts from 0 up to n-1, where n is the total number of items present in the list. We can use the index number of an individual item to access it.

    Example (Access list item)

    programming = ["Python","JavaScript", "Java", "C++",]
    
    #access list item
    program1 = programming[0]
    
    print(program1)    #Python

    Python list also supports negative indexing, which allows us to access list items from the rear side. The negative indexing starts from -1 up to -n, where -1 represents the last item's index number and -n first item.

    Example (Access list item with negative indexing)

    programming = ["Python","JavaScript", "Java", "C++",]
    
    #access list item
    program4 = programming[-1]
    
    print(program4)

    Output

    C++

    That’s enough about the Python list; now, let’s discuss the method supported by a Python list.

    Python List Methods

    A method is a function that is defined for an object. Python list supports many inbuilt functions. To list all the list’s methods, we can use dir() function.

    >>> dir(list)
    
    ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', 
    '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', 
    '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', 
    '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
    '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', 
    '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 
    'insert', 'pop', 'remove', 'reverse', 'sort']

    A list supports 11 normal methods that we generally use, and the rest of the other methods are dunders.  List methods

    1. append()
    2. clear()
    3. copy()
    4. count()
    5. extend()
    6. index()
    7. insert()
    8. pop()
    9. remove()
    10. reverse()
    11. sort()

    1. Python list append method

    The append method is the most used list method. With the append() method, we can add a new item to the list. The append() method adds the new item at the end of the list.

    syntax

    list_name.append(item)

    return The append() method performs the in-place operation on the list and return None.

    argument append() accepts a single argument value.

    Example

    tutorials = ["Python","JavaScript", "Java", "C++"]
    
    #add new program to tutorials list
    tutorials.append("C")
    
    print(tutorials)

    Output

    ['Python', 'JavaScript', 'Java', 'C++', 'C']

    2. Python list clear method

    With the clear() method, we can remove all the items present in the list. The clear() method also performs the in-place operation and returns None as a value.

    syntax

    
    list_name.clear()

    return clear() perform inplace operation on the list and return None

    argument The clear method does not accept any argument value

    Example

    tutorials = ["Python","JavaScript", "Java", "C++"]
    
    #clear all tutorials 
    tutorials.clear()
    
    print(tutorials)

    Output

    []

    3. Python list copy method

    The copy() method creates a shallow copy of the list and returns a new list with the same elements.  A shallow copy means it will only copy the outer items of the list; if the list has a nested list, items those nested list items won’t be copied but referred.

    syntax

    list_name.copy()

    return It returns a shallow copy of the list

    argument It does not accept any argument

    Example

    tutorials = ["Python","JavaScript", "Java", "C++", ["Django", "Flask"]]
    
    #copy tutorials 
    all_tutorials = tutorials.copy()
    
    #add new totorial
    tutorials[4].append("React")
    
    print("Tutorials:",tutorials)
    print("All tutorails:", all_tutorials)

    Output

    Tutorials: ['Python', 'JavaScript', 'Java', 'C++', ['Django', 'Flask', 'React']]
    All tutorails: ['Python', 'JavaScript', 'Java', 'C++', ['Django', 'Flask', 'React']]

    4. Python list count method

    The count() method, count the number of times an item occurs in a list.

    syntax

    list_name.count()

    return It returns an integer value, representing the number of times the object occurs in the list.

    argument It accepts a single argument, the item that we want to count.

    Example

    beverage = ["tea", "coke", "coffee", "red bull", "tea", "juice", "coke", "tea"]
    
    tea_count = beverage.count("tea")
    
    print(f"tea occurs {tea_count} times on beverage list")

    Output

    tea occurs 3 times on beverage list

    5. Python list extend method

    With the append() method, we can only add a single object to the list. But the extend method allows us to add multiple items to the list.  The extend method accepts an iterable object as an argument and adds all the items of the iterable object to the list.

    syntax

    list_name.extend(items)

    return extend() perform the inplace operation and return None

    argument It accepts a single iterable argument, which items we want to add to the list.

    Example

    languages = ["English","Mandarin","Hindi","Spanish"]
    
    #add new languages to the list
    languages.extend(("French", "Arabic", "Bengali"))
    
    print(languages)

    Output

    ['English', 'Mandarin', 'Hindi', 'Spanish', 'French', 'Arabic', 'Bengali']

    6. Python list index method

    With the list’s index() method, we can find the index number of the first occurrence of the item.

    syntax

    list_name.index(item)

    return index() method return an integer value, for the index number.

    argument It accepts a single argument, which index number we want to find.

    Example

    languages = ["English","Mandarin","Hindi","Spanish"]
    
    #find the index value of Hindi
    hindi_idx = languages.index("Hindi")
    
    print("The index value of Hindi in languages is:",hindi_idx)

    Output

    The index value of Hindi in languages is: 2

    If the list has duplicate items, the index() method will return the index value for the first occurrence.

    Example

    ages = [17, 18, 19, 17, 19, 20, 21, 20]
    
    #find the index value of 20
    age_idx = ages.index(20)
    
    print("The index value of 20 in ages is:",age_idx)

    Output

    The index value of 20 in ages is: 5

    The index() method return an error if the specified item does not present in the list.

    Example

    ages = [17, 18, 19, 17, 19, 20, 21, 20]
    
    #find the index value of 20
    age_idx = ages.index(30)
    
    print("The index value of 20 in ages is:",age_idx)

    Output

    ValueError: 30 is not in list

    7. Python list insert method

    The insert() method allows us to add a new item at a specific index position.

    syntax

    list_name.insert(index, item)

    return insert() method add the item in the existing list, and return None.

    argument It accepts two arguments, index and item. The index is the index number where we want to add the new item, and the item is the new item that we want to add to the list.

    Example

    languages = ["English","Mandarin","Spanish"]
    
    #insert Hindi at index number 2
    languages.insert(2, "Hindi")
    
    print(languages)

    Output

    ['English', 'Mandarin', 'Hindi', 'Spanish']

    If we try to add a new item using an index value more than the list’s range, there the insert method will add the item at the end of the list.

    Example

    languages = ["English","Mandarin","Spanish"]
    
    #insert Hindi at index number 100
    languages.insert(100, "Hindi")
    
    print(languages)

    Output

    ['English', 'Mandarin', 'Spanish', 'Hindi']

    8. Python list pop method

    With the help of the list's pop() method, we can remove any item using the item’s index number.

    syntax

    list_name.pop(index)

    return pop() method removes the item from the list and returns that removed item.

    argument It accepts a single argument which is optional. If we do not provide any argument value to the pop method, it will remove and return the last item on the list.

    Example

    languages = ["English","Mandarin","Hindi","Spanish"]
    
    #remove the last element
    removed = languages.pop()
    
    print("The removed item is:", removed)
    print(languages)

    Output

    The removed item is: Spanish
    ['English', 'Mandarin', 'Hindi']

    Example

    languages = ["English","Mandarin","Hindi","Spanish"]
    
    #remove the item which index number is 2
    removed = languages.pop(2)
    
    print("The removed item is:", removed)
    print(languages)

    Output

    The removed item is: Hindi
    ['English', 'Mandarin', 'Spanish']

    If we try to remove an item with an out of range index number, the pop() method will raise the error.

    Example

    languages = ["English","Mandarin","Hindi","Spanish"]
    
    #remove the item which index number is 100
    removed = languages.pop(100)
    
    print("The removed item is:", removed)
    print(languages)

    Output

    IndexError: pop index out of range

    9. Python list remove method

    As the name suggests, with the remove method, we can remove the first occurrence of a specific item from a list.

    syntax

    list_name.remove(item)

    return remove() method remove the item from the list and return None

    argument It accepts a single argument value item that we want to remove from the list.

    Example

    languages = ["English","Mandarin","Hindi","Spanish"]
    
    #remove the item Mandarin
    languages.remove("Mandarin")
    
    print(languages)

    Output

    ['English', 'Hindi', 'Spanish']

    The remove method only removes the first occurrence of the specified item.

    Example

    languages = ["English","Spanish","Mandarin", "Hindi","Spanish"]
    
    #remove the item Spanish
    languages.remove("Spanish")
    
    print(languages)

    Output

    ['English', 'Mandarin', 'Hindi', 'Spanish']

    If we try to remove an item that does not present in the list, the remove method throws the error.

    Example

    languages = ["English","Spanish","Mandarin", "Hindi","Spanish"]
    
    #remove the item French
    languages.remove("French")
    
    print(languages)

    Output

    ValueError: list.remove(x): x not in list

    10. Python list reverse method

    The reverse() method reverses the list of items. This method only reverses the list from back to forth, it does not sort the list in any order.

    syntax

    list_name.reverse()

    return reverse() method reverse the in-place item, and it returns None.

    argument It does not accept any argument value

    Example

    languages = ["English","Mandarin", "Hindi","Spanish"]
    
    #reverse the list
    languages.reverse()
    
    print(languages)

    Output

    ['Spanish', 'Hindi', 'Mandarin', 'English']

    11. Python list sort method

    The sort() method sorts the list items in lexicographical order.

    syntax

    list_name.sort(*, key=None, reverse=False)

    return reverse() performs in-place sorting and return None

    argument It accepts two optional arguments key = The function that performs the sorting comparison. reverse = Boolean value, True for descending sorting and False for ascending sorting.

    Example

    languages = ["English","Mandarin", "Hindi","Spanish"]
    
    #sort the list
    languages.sort()
    
    print(languages)

    Output

    ['English', 'Hindi', 'Mandarin', 'Spanish']

    The sort() method can only sort a list that has a similar data type, else it returns an error.

    Example

    languages = ["English","Mandarin", "Hindi","Spanish", 3]
    
    #sort the list
    languages.sort()
    
    print(languages)

    Output

    TypeError: '<' not supported between instances of 'int' and 'str'

    Conclusion

    A Python list is a mutable data structure, and it is mostly used to store similar data.  In this Python guide, we discussed all the methods that are available for a Python list object. We also discuss their syntax and examples with some exceptions. Method like append(), insert(), remove(), pop(), extend(), sort(), clear and reverse() perform the in-place operation and return None(except pop). And the methods copy(), count(), and index(), do not perform any in-place operation and return some value.

    People are also reading:

    Leave a Comment on this Post

    0 Comments