Skip to main content

Python List Functions & Methods Tutorial

Learn about Python List functions and methods. Follow code examples for list() and other Python functions and methods now!
Jun 2020  · 9 min read

In Python, you can use a list function which creates a collection that can be manipulated for your analysis. This collection of data is called a list object.

While all methods are functions in Python, not all functions are methods. There is a key difference between functions and methods in Python. Functions take objects as inputs. Methods in contrast act on objects.

Python offers the following list functions:

sort() method

The sort() method is a built-in Python method that, by default, sorts the list in ascending order. However, you can modify the order from ascending to descending by specifying the sorting criteria.

Example

Let's say you want to sort the element in prices in ascending order. You would type prices followed by a . (period) followed by the method name, i.e., sort including the parentheses.

prices = [238.11, 237.81, 238.91]
prices.sort()
print(prices)
[237.81, 238.11, 238.91]

type() function

For the type() function, it returns the class type of an object.

Example

Here we will see what type of both fam and fam2 are:

fam = ["liz", 1.73, "emma", 1.68, "mom", 1.71, "dad", 1.89]
fam
['liz', 1.73, 'emma', 1.68, 'mom', 1.71, 'dad', 1.89]

Let's see what the type of the object is:

type(fam)
list

Now, let's look at fam2.

fam2 = [["liz", 1.73],
        ["emma", 1.68],
        ["mom", 1.71],
        ["dad", 1.89]]
fam2
[['liz', 1.73], ['emma', 1.68], ['mom', 1.71], ['dad', 1.89]]

Let's see what the type of the object is:

type(fam2)
list

These calls show that both fam and fam2 are in fact lists.

append() method

The append() method will add certain content you enter to the end of the elements you select.

Example

In this example, let's extend the string by adding "April" to the list with the method append(). Using append() will increase the length of the list by 1.

months = ['January', 'February', 'March']
months.append('April')
print(months)

When you run the above code, it produces the following result:

['January', 'February', 'March', 'April']

extend() method

The extend() method increases the length of the list by the number of elements that are provided to the method, so if you want to add multiple elements to the list, you can use this method.

Example

x = [1, 2, 3]
x.extend([4, 5])
x

When you run the above code, it produces the following result:

[1, 2, 3, 4, 5]

index() method

The index() method returns the first appearance of the specified value.

Example

In the below example, let's look at the index of February in the list months.

months = ['January', 'February', 'March']
prices = [238.11, 237.81, 238.91]
months.index('February')
1

This method helps identify that February is located at index 1. Now we can access the corresponding price of February using this index.

print(prices[1])
237.81

max() function

The max() function will return the highest value of the inputted values.

Example

In this example, we will look to use the max() function to find the maximum price in the list named price.

# Find the maximum price in the list price
prices = [159.54, 37.13, 71.17]
price_max = max(prices)
print(price_max)

When you run the above code, it produces the following result:

159.54

min() function

The min() function will return the lowest value of the inputted values.

Example

In this example, you will find the month with the smallest consumer price index (CPI).

To identify the month with the smallest consumer price index, you first apply the min() function on prices to identify the min_price. Next, you can use the index method to find the index location of the min_price. Using this indexed location on months, you can identify the month with the smallest consumer price index.

months = ['January', 'February', 'March']
prices = [238.11, 237.81, 238.91]
# Identify min price
min_price = min(prices)

# Identify min price index
min_index = prices.index(min_price)

# Identify the month with min price
min_month = months[min_index]
print[min_month]
February

len() function

The len() function shows the number of elements in a list. In the below example, we will look at stock price data again using integers.

Example

stock_price_1 = [50.23]
stock_price_2 = [75.14, 85.64, 11.28]

print('stock_price_1 length is ', len(stock_price_1))
print('stock_price_2 length is ', len(stock_price_2))

When you run the above code, it produces the following result:

stock_price_1 length is 1
stock_price_2 length is 3

list() function

The list() function takes an iterable construct and turns it into a list.

Syntax

list([iterable])

Example

In the below example, you will be working with stock price data. Let's print out an empty list, convert a tuple into a list, and finally, print a list as a list.

# empty list
print(list())

# tuple of stock prices
stocks = ('238.11', '237.81', '238.91')
print(list(stocks))

# list of stock prices
stocks_1 = ['238.11', '237.81', '238.91']
print(list(stocks_1))

When you run the above code, it produces the following result:

[]
['238.11', '237.81', '238.91']
['238.11', '237.81', '238.91']

cmp() function

For the cmp() function, it takes two values and compares them against one another. It will then return a negative, zero, or positive value based on what was inputted.

Example

In the example below, we have two stock prices, and we will compare the integer values to see which one is larger:

stock_price_1 = [50.23]
stock_price_2 = [75.14]

print(cmp(stock_price_1, stock_price_2))
print(cmp(stock_price_1, stock_price_1))
print(cmp(stock_price_2, stock_price_1))

When you run the above code, it produces the following result:

-1
0
1

The results show that the stock_price_2 list is larger than the stock_price_1 list. You can use the cmp() function on any type of list, such as strings. Note that by default, if one list is longer than the other, it will be considered to be larger.

To learn more about list methods and functions, please see this video from our course Introduction to Python for Finance.

This content is taken from DataCamp's Introduction to Python for Finance course by Adina Howe.

Python List Functions & Methods

What is a list in Python?
One of the main built-in data structures in Python is storing any number of items. The main characteristics of Python lists are that they are iterable, ordered, indexed, mutable, and allow duplicated values.

How to make a list in Python?
Place a sequence of items inside square brackets and separate them by comma, e.g., ['cake', 'ice-cream', 'donut']. Alternatively, use the list() built-in function with double brackets: list(('cake', 'ice-cream', 'donut')). To create an empty list, use empty square brackets ([]) or the list() function without passing any argument (list()). Usually, a Python list is assigned to a variable for further usage.

What is a Python list used for?
When we need to keep together multiple related items placed in a defined order, possibly of heterogeneous data types and/or with duplicates. We then want to be able to modify those items, add or remove items, and apply the same operations on several values at once.

What kinds of objects can a Python list contain?
Any kinds of Python objects, both primitive (integers, floats, strings, boolean) and complex (other lists, tuples, dictionaries, etc.). There can be different data types in one Python list, e.g., ['cake', 1, 3.14, [0, 2]], which makes this data structure very flexible.

Is a Python list ordered?
Yes. The items of a Python list have a fixed order, which makes this data structure also indexed. Each item of a Python list has an index corresponding to its position in the list, starting from 0 for the first item. The last item of a Python list has the index N-1, where N is the number of items in the list.

Is a Python list mutable?
Yes. The values of the items in a Python list can be modified after the list is created, with no need to reassign the list to a variable. The items can also be added or removed, resulting in dynamically changing the size of the list.

Does a Python list allow duplicate values?
Yes. Because these data structures are ordered and indexed, a Python list can contain any number of repeated items.

What is the difference between append() and extend()?
While the append() method allows adding a single item at the end of a Python list, the extend() method allows adding multiple items. In the first case, the length of a list is increased by 1; in the second, the length is increased by the number of added items.

What is the difference between sort() and sorted()?
While the sort() method doesn't return anything and modifies the original list, the sorted() function returns a sorted list but doesn't modify the original list. If we want to save the result of applying the sorted() function for further usage we have to assign it to a variable.

What is the difference between a tuple and a list in Python?
The main difference is that lists are mutable and tuples are immutable, meaning that the items of a Python list can be changed while those of a Python tuple cannot. As a consequence, these two data structures have different methods available. Also, tuples are faster and consume less memory than lists.

Introduction to Python

Beginner
4 hours
4,596,583
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See DetailsRight Arrow
Start Course

Intermediate Python

Beginner
4 hours
883,269
Level up your data science skills by creating visualizations using Matplotlib and manipulating DataFrames with pandas.

Python Data Science Toolbox (Part 2)

Beginner
4 hours
225,476
Continue to build your modern Data Science skills by learning about iterators and list comprehensions.
See all coursesRight Arrow
Related

The 23 Top Python Interview Questions & Answers

Essential Python interview questions with examples for job seekers, final-year students, and data professionals.
Abid Ali Awan's photo

Abid Ali Awan

22 min

Working with Dates and Times in Python Cheat Sheet

Working with dates and times is essential when manipulating data in Python. Learn the basics of working with datetime data in this cheat sheet.
DataCamp Team's photo

DataCamp Team

Plotly Express Cheat Sheet

Plotly is one of the most widely used data visualization packages in Python. Learn more about it in this cheat sheet.
DataCamp Team's photo

DataCamp Team

0 min

Getting started with Python cheat sheet

Python is the most popular programming language in data science. Use this cheat sheet to jumpstart your Python learning journey.
DataCamp Team's photo

DataCamp Team

8 min

Python pandas tutorial: The ultimate guide for beginners

Are you ready to begin your pandas journey? Here’s a step-by-step guide on how to get started. [Updated November 2022]
Vidhi Chugh's photo

Vidhi Chugh

15 min

Python Iterators and Generators Tutorial

Explore the difference between Python Iterators and Generators and learn which are the best to use in various situations.
Kurtis Pykes 's photo

Kurtis Pykes

10 min

See MoreSee More