What is Python List?
A list is a sequence of values (similar to an array in other programming languages but more versatile)
The values in a list are called items or sometimes elements.
The important properties of Python lists are as follows:
- Lists are ordered – Lists remember the order of items inserted.
- Accessed by index – Items in a list can be accessed using an index.
- Lists can contain any sort of object – It can be numbers, strings, tuples and even other lists.
- Lists are changeable (mutable) – You can change a list in-place, add new items, and delete or update existing items.
Create a List
There are several ways to create a new list; the simplest is to enclose the values in square brackets []
# A list of integers
L = [1, 2, 3]
# A list of strings
L = ['red', 'green', 'blue']
The items of a list don’t have to be the same type. The following list contains an integer, a string, a float, a complex number, and a boolean.
# A list of mixed datatypes
L = [ 1, 'abc', 1.23, (3+4j), True]
A list containing zero items is called an empty list and you can create one with empty
brackets []
# An empty list
L = []
There is one more way to create a list based on existing list, called List comprehension.
The list() Constructor
You can convert other data types to lists using Python’s list() constructor.
# Convert a string to a list
L = list('abc')
print(L)
# Prints ['a', 'b', 'c']
# Convert a tuple to a list
L = list((1, 2, 3))
print(L)
# Prints [1, 2, 3]
Nested List
A list can contain sublists, which in turn can contain sublists themselves, and so on. This is known as nested list.
You can use them to arrange data into hierarchical structures.
L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']
Read more about it in the nested list tutorial.
Access List Items by Index
You can think of a list as a relationship between indexes and values. This relationship is called a mapping; each index maps to one of the values. The indexes for the values in a list are illustrated as below:
Note that the first element of a list is always at index zero.
You can access individual items in a list using an index in square brackets.
L = ['red', 'green', 'blue', 'yellow', 'black']
print(L[0])
# Prints red
print(L[2])
# Prints blue
Python will raise an IndexError
error, if you use an index that exceeds the number of items in your list.
L = ['red', 'green', 'blue', 'yellow', 'black']
print(L[10])
# Triggers IndexError: list index out of range
Negative List Indexing
You can access a list by negative indexing as well. Negative indexes count backward from the end of the list. So, L[-1]
refers to the last item, L[-2]
is the second-last, and so on.
The negative indexes for the items in a list are illustrated as below:
L = ['red', 'green', 'blue', 'yellow', 'black']
print(L[-1])
# Prints black
print(L[-2])
# Prints yellow
Access Nested List Items
Similarly, you can access individual items in a nested list using multiple indexes. The first index determines which list to use, and the second indicates the value within that list.
The indexes for the items in a nested list are illustrated as below:
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']
print(L[2][2])
# Prints ['eee', 'fff']
print(L[2][2][0])
# Prints eee
Slicing a List
A segment of a list is called a slice and you can extract one by using a slice operator. A slice of a list is also a list.
The slice operator [n:m] returns the part of the list from the “n-th” item to the “m-th” item, including the first but excluding the last.
L = ['a', 'b', 'c', 'd', 'e', 'f']
print(L[2:5])
# Prints ['c', 'd', 'e']
print(L[0:2])
# Prints ['a', 'b']
print(L[3:-1])
# Prints ['d', 'e']
Read more about it in the list slicing tutorial.
Change Item Value
You can replace an existing element with a new value by assigning the new value to the index.
L = ['red', 'green', 'blue']
L[0] = 'orange'
print(L)
# Prints ['orange', 'green', 'blue']
L[-1] = 'violet'
print(L)
# Prints ['orange', 'green', 'violet']
Add items to a list
To add new values to a list, use append() method. This method adds items only to the end of the list.
L = ['red', 'green', 'yellow']
L.append('blue')
print(L)
# Prints ['red', 'green', 'yellow', 'blue']
If you want to insert an item at a specific position in a list, use insert() method. Note that all of the values in the list after the inserted value will be moved down one index.
L = ['red', 'green', 'yellow']
L.insert(1,'blue')
print(L)
# Prints ['red', 'blue', 'green', 'yellow']
Combine Lists
You can merge one list into another by using extend() method. It takes a list as an argument and appends all of the elements.
L = ['red', 'green', 'yellow']
L.extend([1,2,3])
print(L)
# Prints ['red', 'green', 'yellow', 1, 2, 3]
Alternatively, you can use the concatenation operator +
or the augmented assignment operator +=
# concatenation operator
L = ['red', 'green', 'blue']
L = L + [1,2,3]
print(L)
# Prints ['red', 'green', 'blue', 1, 2, 3]
# augmented assignment operator
L = ['red', 'green', 'blue']
L += [1,2,3]
print(L)
# Prints ['red', 'green', 'blue', 1, 2, 3]
Remove items from a list
There are several ways to remove items from a list.
Remove an Item by Index
If you know the index of the item you want, you can use pop() method. It modifies the list and returns the removed item.
If no index is specified, pop()
removes and returns the last item in the list.
L = ['red', 'green', 'blue']
x = L.pop(1)
print(L)
# Prints ['red', 'blue']
# removed item
print(x)
# Prints green
If you don’t need the removed value, use the del statement.
L = ['red', 'green', 'blue']
del L[1]
print(L)
# Prints ['red', 'blue']
Remove an Item by Value
If you’re not sure where the item is in the list, use remove() method to delete it by value.
L = ['red', 'green', 'blue']
L.remove('red')
print(L)
# Prints ['green', 'blue']
But keep in mind that if more than one instance of the given item is present in the list, then this method removes only the first instance.
L = ['red', 'green', 'blue', 'red']
L.remove('red')
print(L)
# Prints ['green', 'blue', 'red']
Remove Multiple Items
To remove more than one items, use the del keyword with a slice index.
L = ['red', 'green', 'blue', 'yellow', 'black']
del L[1:4]
print(L)
# Prints ['red', 'black']
Remove all Items
Use clear() method to remove all items from the list.
L = ['red', 'green', 'blue']
L.clear()
print(L)
# Prints []
List Replication
The replication operator *
repeats a list a given number of times.
L = ['red']
L = L * 3
print(L)
# Prints ['red', 'red', 'red']
Find List Length
To find the number of items in a list, use len() method.
L = ['red', 'green', 'blue']
print(len(L))
# Prints 3
Check if item exists in a list
To determine whether a value is or isn’t in a list, you can use in and not in operators with if statement.
# Check for presence
L = ['red', 'green', 'blue']
if 'red' in L:
print('yes')
# Check for absence
L = ['red', 'green', 'blue']
if 'yellow' not in L:
print('yes')
Iterate through a List
The most common way to iterate through a list is with a for loop.
L = ['red', 'green', 'blue']
for item in L:
print(item)
# Prints red
# Prints green
# Prints blue
This works well if you only need to read the items of the list. But if you want to update them, you need the indexes. A common way to do that is to combine the range()
and len()
functions.
# Loop through the list and double each item
L = [1, 2, 3, 4]
for i in range(len(L)):
L[i] = L[i] * 2
print(L)
# Prints [2, 4, 6, 8]
Python List Methods
Python has a set of built-in methods that you can call on list objects.
Method | Description |
append() | Adds an item to the end of the list |
insert() | Inserts an item at a given position |
extend() | Extends the list by appending all the items from the iterable |
remove() | Removes first instance of the specified item |
pop() | Removes the item at the given position in the list |
clear() | Removes all items from the list |
copy() | Returns a shallow copy of the list |
count() | Returns the count of specified item in the list |
index() | Returns the index of first instance of the specified item |
reverse() | Reverses the items of the list in place |
sort() | Sorts the items of the list in place |
Built-in Functions with List
Python also has a set of built-in functions that you can use with list objects.
Method | Description |
all() | Returns True if all list items are true |
any() | Returns True if any list item is true |
enumerate() | Takes a list and returns an enumerate object |
len() | Returns the number of items in the list |
list() | Converts an iterable (tuple, string, set etc.) to a list |
max() | Returns the largest item of the list |
min() | Returns the smallest item of the list |
sorted() | Returns a sorted list |
sum() | Sums items of the list |