Python List

Introduction

A Python list is a collection of ordered items. Lists can hold a mix of items of any data type and can also change their size.

Consequently, Python lists are very easy to use. However, their flexible nature comes at the expense of performance (speed and space usage) as well as an increased potential for bugs. These are common tradeoffs that come with ease of use and flexibility.

List Literals

A list literal is defined using square brackets [] and consists of comma separated items inside.

Example:

[1, "two", 3, "four", 5]

The example above shows a list definition with a mix of integer and string items.

A list with just one item doesn’t need any commas, [1].

But adding a comma at the end is not an error:

[1,]  # No error!

In fact, adding a comma to the end of bigger lists is also legal:

[1, 2, 3,]  # It'll work!

But you shouldn’t be putting extra commas where they are not needed!

Here is another example, which is a list of strings:

["I", "know", "about", "lists"]

Creating Empty Lists

An empty list is written with just brackets [].

Example:

empty_list = []

The Python List Constructor

Lists can be created using the list() constructor function by passing any iterable object. An iterable is an object that implement a standard Python protocol for returning items in a sequence. The list() constructor will convert the sequence into a list containing items in the same order.

For instance, a Python range specifies a sequence of integers from lowest to highest and can easily be made into a list.

Example:

my_range = range(1, 5)  # A range of integers from 1 to 4 (one less than the last number)
print(list(my_range))

Output:

 [1, 2, 3, 4]

Here is another example, which constructs a list out of a string:

print(list("abcde"))

Output:

['a', 'b', 'c', 'd', 'e']

Finding the Length of a List

To work effectively with lists, it’s often useful to know how many elements are present in the list.

Python provides a built-in function called len() that returns the length of a list, i.e., the number of items it contains.

Example:

my_list = [1, "two", 3, "four", 5]
list_length = len(my_list)
print(list_length)

Output:

5

len() will work with other Python objects that are iterable. Iterables are objects that define an interface to fetch items from within one by one. Examples of iterables include strings and ranges.

List Indexing

In a list, each item has a designated position or location called an index.

An index specifies how many positions an item is offset from the beginning of the list, and therefore, the index of the first item is 0, since it is not offset from the beginning at all.

In the following list,

["This", "is", "a", "list", "with", "words."]

The string “This” is at the first position with an index of 0. “is” has an index of 1, and the index keeps going up with each item until we reach the last item. “words.” is in the sixth and last position with an index of 5.

Notice how each index is one less than its position. This can be a potential source of bugs and confusion for people new to programming.

Accessing Items in a List

A single item can be accessed by placing its index inside of square brackets [] following the list.

The example below first assigns a list to the variable vehicles, and then prints the list item at index 2, which is “truck”.

Example:

vehicles = ["airplane", "car", "truck", "boat", "rocket"]
print(vehicles[2])

Output:

truck

If you try to access an index position that is not in the list, you’ll get an error.

vehicles = ["airplane", "car", "truck", "boat", "rocket"]
vehicles[5]

Output:

...
IndexError: list index out of range

Assigning Items to a List

To assign an item in a list, you also use the square brackets to specify the index of the list position and then assign it with the equal sign = like any other variable.

vehicles = ["airplane", "car", "truck", "boat", "rocket"]
vehicles[1] = "helicopter"
print(vehicles)

Output:

['airplane', 'helicopter', 'truck', 'boat', 'rocket']

After the assignment, “car” changes to “helicopter” inside the vehicles list.

Data structures that can be internally changed are said to be mutable.

Some other data structures in Python, such as tuples, cannot be changed and are immutable.

Negative Indexes

Indexes can be negative.

All this means is that the position is specified from the end of the list back to the start, with the last item having the index -1.

The next-to-last item has index -2, etc., all the way to the first element, which has the index of negative whatever-the-length-of-the-list-is.

vehicles = ["airplane", "car", "truck", "boat", "rocket"]
print(vehicles[-1])
print(vehicles[-2])
print(vehicles[-5])

Output:

rocket
boat
airplane

List Operations

Appending an Item to a List

You can add an item to the end of a list by using the append() method of a list.

append() will add the item it’s given to the end of the list.

my_list = [1, 2, 3, 4]
my_list.append(5)
print(my_list)

Output:

[1, 2, 3, 4, 5]

Note how append() modified the list assigned to the variable my_list by adding the item 5 to the end and thereby also changing its size.

This is in contrast to the concatenation operation, which you’ll learn about in a subsequent section, that adds elements to a list by creating a new one and leaving the original list unchanged.

Inserting an Item Within a List

You can insert an item at any index position in a list by using the insert() method.

insert() has two parameters: the index position and the item to insert.

Example:

my_list = [1, 2, 3, 4]
my_list.insert(2, 2.5)
print(my_list)

Output:

[1, 2, 2.5, 3, 4]

Like append(), insert() modifies the original list.

Popping an Item From a List

A pop operation removes an item from a list and returns it.

The pop() method will pop the last item if it’s not given an argument, and it can also pop an item from a specified index position, given as an argument.

Example:

my_list = [1, 2, 3, 4]
popped = my_list.pop()
print(popped)
print(my_list)

Output:

4
[1, 2, 3]

In the above example pop() is used without an argument, and therefore, pops the last item in the list, 4.

The next example will pop an item from a specified index, given as an argument to pop().

Example:

my_list = [1, 2, 3, 4]
popped = my_list.pop(1)
print(popped)
print(my_list)

Output:

2
[1, 3, 4]

In this example, the popped item, the number 2, is removed from index position 1.

Deleting an Item From a List

You can also delete items from a list at a specific index position using the del statement. When using del the deleted item removed without being returned.

del is a generic Python statement used to delete variables, objects, and attributes, and its syntax is different from that of the list operations above.

With del, deletion is done by writing del followed by the item to be deleted.

Example:

my_list = [1, 2, 3, 4]
del my_list[2]
print(my_list)

Output:

[1, 2, 4]

The example above deletes the item at index position 2 by using the del keyword with the item itself, as obtained by indexing my_list with 2.

List Concatenation

Concatenation is the process of linking things together. In Python, you can concatenate two or more lists by placing the + operator between them. The result is a new list with all the elements of the first, followed by all the elements of the second.

Example:

my_list_1 = [1, 2, 3]
my_list_2 = [4, 5, 6]
my_list_1_and_2 = my_list_1 + my_list_2
print(my_list_1_and_2)

Output:

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

And both my_list_1 and my_list_2 don’t change:

print(my_list_1)
print(my_list_2)

Output:

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

Nested Lists

Since Python lists can contain anything, they can also contain other lists. When a list contains other lists as its elements, it is referred to as a “list within a list” or a “nested list.” This concept allows you to create more complex and useful data structures, such as two-dimensional lists or matrices.

Example:

two_dim_list = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

In the example above, the list two_dim_list contains three lists, each with four elements. two_dim_list can be considered a two-dimensional list, or matrix with three rows and four columns.

To access a specific row, you use the first index.

Example:

second_row = two_dim_list[1]
print(second_row)

Output:

[5, 6, 7, 8]

You can access items within a nested list by using multiple indices. The first index specifies the sublist, and the second index indicates the element within that sublist.

Example:

print(two_dim_list[0][0])
print(two_dim_list[1][2])

Output:

1
7

To assign elements within a nested list, you can use the same indexing syntax.

two_dim_list[1][2] = 42
print(two_dim_list)

Output:

[[1, 2, 3, 4], [5, 6, 42, 8], [9, 10, 11, 12]]

You can also, of course, go to higher dimensions by increasing the nesting.

Example:

three_dim_list = [
    [[1, 2], [3, 4], [5, 6], [7, 8]],
    [[9, 10], [11, 12], [13, 14], [15, 16]],
    [[17, 18], [19, 20], [21, 22], [23, 24]]
]

The above example creates a list that represents a 3x4x2-dimensional data structure.

Because of the flexibility of Python lists, it is possible to create a nested list with inconsistent dimensions, which might lead to errors and bugs.

Example:

two_dim_list = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]

Here the first two nested arrays have 4 items, and the last one 3.

Attempting to access the fourth item of the last list will give an error.

Example:

two_dim_list[0][3]   # No error
two_dim_list[1][3]   # No error
two_dim_list[2][4]   # IndexError: list index out of range

Summary & Reference for Python List

A list is a collection of ordered items. It can hold a mix of data types and change in size.


Lists can be defined directly using list literals that are square brackets [] with comma-separated items inside.

my_list = [1, "two", 3, "four", 5]

[] is the empty list literal.


The list() function is a constructor that creates lists from various Python objects that can be converted into a list in a meaningful way.

list(range(1, 5))  # --> [1, 2, 3, 4]

The len() function returns the length of a list.

len(my_list)  # --> 5

List items are accessed using square brackets [] and an integer index, with the first item having index 0, second item index 1, etc.

my_list[2]  # --> 3

Negative indexes can be used to access items from the end of the list, with the last item having index -1, next to last -2, etc.

my_list[-1]  # --> 5

List items can be assigned or changed using their index.

my_list[1] = "the number one"

Use append() to add an item to the end of a list.

my_list.append("six")  # my_list --> [1, "two", 3, "four", 5, "six"]

Use insert() to add an item at a specific index in a list.

my_list.insert(2, 2.5)  # my_list --> [1, "two", 2.5, 3 "four", 5, "six"]

pop() with no argument removes and returns the last item in the list.

popped_item = my_list.pop()  # popped_item --> 5    my_list --> [1, "two", 3, "four"]

pop() with an argument removes and returns the item at the specified index.

popped_item = my_list.pop(1)  # popped_item --> "two"    my_list --> [1, 3, "four", 5]

Use del to delete an item at a specific index from the list. del does not return the delete item.

del my_list[1]   # my_list --> [1, 3, "four", 5]

Concatenate two or more lists using the + operator to create a new list, without changing the originals..

new_list = my_list + [6, 7]  # new_list --> [1, "two", 3, "four", 5, 6, 7]

Nested lists are lists that contain other lists as elements.

nested_list = [[1, 2], [3, 4]]

Access elements in a nested list using multiple indexes.

nested_list[1][0]  # --> 3