The Wayback Machine - https://web.archive.org/web/20241013185224/https://www.geeksforgeeks.org/list-methods-python/
Open In App

Python List methods

Last Updated : 18 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python List Methods are the built-in methods in lists used to perform operations on Python lists/arrays.

Below, we’ve explained all the Python list methods you can use with Python lists, for example, append(), copy(), insert(), and more.

List Methods in Python

Let’s look at some different list methods in Python for Python lists:

S.noMethodDescription
1append()Used for adding elements to the end of the List. 
2copy()It returns a shallow copy of a list
3clear()This method is used for removing all items from the list. 
4count()These methods count the elements.
5extend()Adds each element of an iterable to the end of the List
6index()Returns the lowest index where the element appears. 
7insert()Inserts a given element at a given index in a list. 
8pop()Removes and returns the last value from the List or the given index value.
9remove()Removes a given object from the List. 
10reverse()Reverses objects of the List in place.
11sort()Sort a List in ascending, descending, or user-defined order
12min()Calculates the minimum of all the elements of the List
13max()Calculates the maximum of all the elements of the List

This article is an extension of the below articles:

Adding Element in List in Python

Let’s look at some built-in list functions in Python to add element in a list.

1. Python append() Method

Adds element to the end of a list.

Syntax: list.append (element)

Example:

Python3
# Adds List Element as value of List.
List = ['Mathematics', 'chemistry', 1997, 2000]
List.append(20544)
print(List)

Output
['Mathematics', 'chemistry', 1997, 2000, 20544]


2. Python insert() Method

Inserts an element at the specified position. 

Syntax:

list.insert(<position, element)

Note: The position mentioned should be within the range of List, as in this case between 0 and 4, else wise would throw IndexError. 

Example:

Python3
List = ['Mathematics', 'chemistry', 1997, 2000]
# Insert at index 2 value 10087
List.insert(2, 10087)
print(List)

Output
['Mathematics', 'chemistry', 10087, 1997, 2000]


3. Python extend() Method

Adds items of an iterable(list, array, string , etc.) to the end of a list.

Syntax: List1.extend(List2)

Example:

Python3
List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]

# Add List2 to List1
List1.extend(List2)
print(List1)

# Add List1 to List2 now
List2.extend(List1)
print(List2)

Output
[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]


Important Functions of the Python List

We have mentioned some essential Python list functions along with their syntax and example:

1. Python sum() Method

Calculates the sum of all the elements of the List. 

Syntax: sum(List)

Example:

Python3
List = [1, 2, 3, 4, 5]
print(sum(List))

Output
15


What happens if a numeric value is not used as a parameter? 

The sum is calculated only for numeric values, else wise throws TypeError. 

See example: 

Python3
List = ['gfg', 'abc', 3]
print(sum(List))

Output:

Traceback (most recent call last):
  File "", line 1, in 
    sum(List)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

2. Python count() Method

Calculates the total occurrence of a given element of the List. 

Syntax: List.count(element)

Example:

Python3
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))

Output
4


3. Python len() Method

Calculates the total length of the List. 

Syntax: len(list_name)

Example:

Python3
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(len(List))

Output
10


4. Python index() Method

Returns the index of the first occurrence. The start and end indexes are not necessary parameters. 

Syntax: List.index(element[,start[,end]])

Example:

Python3
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2))

Output
1


Another example: 

In this example, we are using index() method which is one of the list functions in Python, searching the first occurrence of the element 2, starting from index 2 in the list.

Python3
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2, 2))

Output
4


5. Python min() Method

Calculates minimum of all the elements of List.

Syntax: min(iterable, *iterables[, key])

Example:

Python3
numbers = [5, 2, 8, 1, 9]
print(min(numbers))

Output
1


6. Python max() Method

Calculates the maximum of all the elements of the List.

Syntax: max(iterable, *iterables[, key])

Example:

Python3
numbers = [5, 2, 8, 1, 9]
print(max(numbers))

Output
9


7. Python sort() Method

Sort the given data structure (both tuple and list) in ascending order.

Key and reverse_flag are not necessary parameter and reverse_flag is set to False if nothing is passed through sorted(). 

Syntax: list.sort([key,[Reverse_flag]])

Example:

Python
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]

#Reverse flag is set True
List.sort(reverse=True) 

#List.sort().reverse(), reverses the sorted list  
print(List)        

Output
[5.33, 4.445, 3, 2.5, 2.3, 1.054]


8. Python reverse() Method

reverse() function reverses the order of list.

Syntax: list. reverse()

Example:

Python3
# creating a list
list = [1,2,3,4,5]
#reversing the list
list.reverse()
#printing the list
print(list)

Output
[5, 4, 3, 2, 1]


Deletion of List Elements

To Delete one or more elements, i.e. remove an element, many built-in Python list functions can be used, such as pop() and remove() and keywords such as del.

1. Python pop() Method

Removes an item from a specific index in a list.

Syntax: list.pop([index])

The index is not a necessary parameter, if not mentioned takes the last index. 

Note: The index must be in the range of the List, elsewise IndexErrors occur. 

Example 1:

Python3
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
print(List.pop())

Output
2.5


Example 2:

Python3
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
print(List.pop(0))

Output
2.3


2. Python del() Method

Deletes an element from the list using it’s index.

Syntax: del list.[index]

Example:

Python3
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
del List[0]
print(List)

Output
[4.445, 3, 5.33, 1.054, 2.5]


3. Python remove() Method

Removes a specific element using it’s value/name.

Syntax: list.remove(element)

Example :

Python3
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
List.remove(3)
print(List)

Output
[2.3, 4.445, 5.33, 1.054, 2.5]


We have discussed all major Python list functions, that one should know to work on list. We have seen how to add and remove elements from list and also perform basic operations like count , sort, reverse using list Python Methods.

Hope these Python methods were of help!



Similar Reads

List Methods in Python | Set 1 (in, not in, len(), min(), max()...)
List methods are discussed in this article. 1. len() :- This function returns the length of list. List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] print(len(List)) Output: 10 2. min() :- This function returns the minimum element of list. List = [2.3, 4.445, 3, 5.33, 1.054, 2.5] print(min(List)) Output: 1.054 3. max() :- This function returns the maximum eleme
2 min read
Advanced Python List Methods and Techniques
Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it a most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creati
6 min read
List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...)
Some of the list methods are mentioned in set 1 below List Methods in Python | Set 1 (in, not in, len(), min(), max()…) More methods are discussed in this article. 1. del[a : b] :- This method deletes all the elements in range starting from index 'a' till 'b' mentioned in arguments. 2. pop() :- This method deletes the element at the position mentio
4 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Python String Methods | Set 1 (find, rfind, startwith, endwith, islower, isupper, lower, upper, swapcase & title)
Some of the string basics have been covered in the below articles Strings Part-1 Strings Part-2 The important string methods will be discussed in this article1. find("string", beg, end) :- This function is used to find the position of the substring within a string.It takes 3 arguments, substring , starting index( by default 0) and ending index( by
4 min read
Python String Methods | Set 2 (len, count, center, ljust, rjust, isalpha, isalnum, isspace & join)
Some of the string methods are covered in the set 3 below String Methods Part- 1 More methods are discussed in this article 1. len() :- This function returns the length of the string. 2. count("string", beg, end) :- This function counts the occurrence of mentioned substring in whole string. This function takes 3 arguments, substring, beginning posi
4 min read
Python String Methods | Set 3 (strip, lstrip, rstrip, min, max, maketrans, translate, replace & expandtabs())
Some of the string methods are covered in the below sets.String Methods Part- 1 String Methods Part- 2More methods are discussed in this article1. strip():- This method is used to delete all the leading and trailing characters mentioned in its argument.2. lstrip():- This method is used to delete all the leading characters mentioned in its argument.
4 min read
Accessing Attributes and Methods in Python
Attributes of a class are function objects that define corresponding methods of its instances. They are used to implement access controls of the classes. Attributes of a class can also be accessed using the following built-in methods and functions : getattr() - This function is used to access the attribute of object. hasattr() - This function is us
3 min read
Python | Float type and its methods
The float type in Python represents the floating point number. Float is used to represent real numbers and is written with a decimal point dividing the integer and fractional parts. For example, 97.98, 32.3+e18, -32.54e100 all are floating point numbers. Python float values are represented as 64-bit double-precision values. The maximum value any fl
3 min read
Bound, unbound, and static methods in Python
Methods in Python are like functions except that it is attached to an object.The methods are called on objects and it possibly make changes to that object. These methods can be Bound, Unbound or Static method. The static methods are one of the types of Unbound method. These types are explained in detail below. Bound methods If a function is an attr
5 min read
Http Request methods - Python requests
Python requests module has several built-in methods to make Http requests to specified URI using GET, POST, PUT, PATCH or HEAD requests. A Http request is meant to either retrieve data from a specified URI or to push data to a server. It works as a request-response protocol between a client and server. A web browser may be the client, and an applic
7 min read
Response Methods - Python requests
When one makes a request to a URI, it returns a response. This Response object in terms of python is returned by requests.method(), method being - get, post, put, etc. Response is a powerful object with lots of functions and attributes that assist in normalizing data or creating ideal portions of code. For example, response.status_code returns the
5 min read
Accessor and Mutator methods in Python
In Python, class is a prototype for objects which is a user-defined type. It specifies and defines objects of the same type, a class includes a cluster of data and method definitions. Moreover, an object is a single instance of a class but you can create many objects from a single class.Note: For more information, refer to Python Classes and Object
3 min read
10 Python File System Methods You Should Know
While programming in any language, interaction between the programs and the operating system (Windows, Linux, macOS) can become important at some point in any developer's life. This interaction may include moving files from one location to another, creating a new file, deleting a file, etc. In this article, we will discuss 10 essential file system
6 min read
Element methods in Selenium Python
Selenium’s Python Module is built to perform automated testing with Python. Selenium in Python works with elements. An element can be a tag, property, or anything, it is an instance of class selenium.webdriver.remote.webelement.WebElement. After you find an element on screen using selenium, you might want to click it or find sub-elements, etc. Sele
3 min read
Web Driver Methods in Selenium Python
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What
5 min read
Methods of Ordered Dictionary in Python
An OrderedDict is a dict that remembers the order in that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end. Ordered dictionary somehow can be used in the place where there is a use of hash Map and queue. It has chara
3 min read
Customize your Python class with Magic or Dunder methods
The magic methods ensure a consistent data model that retains the inherited feature of the built-in class while providing customized class behavior. These methods can enrich the class design and can enhance the readability of the language. So, in this article, we will see how to make use of the magic methods, how it works, and the available magic m
13 min read
Subclass and methods of Shelve class in Python
Shelve is a module in Python's standard library which can be used as a non-relational database. The key difference between a dbm and shelve is that shelve can serve its values as any arbitrary object which can be handled by pickle module while in dbm database we can only have standard datatypes of Python as its database values. The key in shelve is
4 min read
Python Tuple Methods
Python Tuples is an immutable collection of that are more like lists. Python Provides a couple of methods to work with tuples. In this article, we will discuss these two methods in detail with the help of some examples. Count() MethodThe count() method of Tuple returns the number of times the given element appears in the tuple. Syntax: tuple.count(
3 min read
Python Set Methods
A Set in Python is a collection of unique elements which are unordered and mutable. Python provides various functions to work with Set. In this article, we will see a list of all the functions provided by Python to deal with Sets. Adding and Removing elementsWe can add and remove elements form the set with the help of the below functions - add(): A
2 min read
Python Input Methods for Competitive Programming
Python is an amazingly user-friendly language with the only flaw of being slow. In comparison to C, C++, and Java, it is quite slower. In online coding platforms, if the C/C++ limit provided is x. Usually, in Java time provided is 2x, and in Python, it's 5x. To improve the speed of code execution for input/output intensive problems, languages have
6 min read
Analysis of Different Methods to find Prime Number in Python
If you participate in competitive programming, you might be familiar with the fact that questions related to Prime numbers are one of the choices of the problem setter. Here, we will discuss how to optimize your function which checks for the Prime number in the given set of ranges, and will also calculate the timings to execute them. Going by defin
7 min read
Define and Call Methods in a Python Class
In object-oriented programming, a class is a blueprint for creating objects, and methods are functions associated with those objects. Methods in a class allow you to define behavior and functionality for the objects created from that class. Python, being an object-oriented programming language, provides a straightforward syntax for defining and cal
3 min read
Private Methods in Python
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP) in Python. It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data. A class is an example of encapsulation as i
6 min read
Bound methods python
A bound method is the one which is dependent on the instance of the class as the first argument. It passes the instance as the first argument which is used to access the variables and functions. In Python 3 and newer versions of python, all functions in the class are by default bound methods. Let's understand this concept with an example: [GFGTABS]
4 min read
Python String Methods
Python string methods is a collection of in-built Python functions that operates on lists. Note: Every string method in Python does not change the original string instead returns a new string with the changed attributes. Python string is a sequence of Unicode characters that is enclosed in quotation marks. In this article, we will discuss the in-bu
6 min read
Dunder or magic methods in Python
Python Magic methods are the methods starting and ending with double underscores '__'. They are defined by built-in classes in Python and commonly used for operator overloading.  They are also called Dunder methods, Dunder here means "Double Under (Underscores)". Python Magic MethodsBuilt in classes define many magic methods, dir() function can sho
7 min read
Python Dictionary Methods
Python dictionary methods is collection of Python functions that operates on Dictionary. Python Dictionary is like a map that is used to store data in the form of a key: value pair. Python provides various built-in functions to deal with dictionaries. In this article, we will see a list of all the functions provided by Python to work with dictionar
5 min read
Dictionary Methods ( Part 1 )
1. str(dic) :- This method is used to return the string, denoting all the dictionary keys with their values. 2. items() :- This method is used to return the list with all dictionary keys with values. # Python code to demonstrate working of # str() and items() # Initializing dictionary dic = { 'Name' : 'Nandini', 'Age' : 19 } # using str() to displa
2 min read
Practice Tags :