Skip to article frontmatterSkip to article content

Chapter 2.5 - Lists

Full name: list

Python keyword: list

Python data type group: sequence

A list is an ordered collection of primitive (or even composite/sequential) data types. A list can be modified by adding, removing, or changing the values of the items contained in the list. To access values in the list, you use indexing (just like with strings!). Indexing values start at 0, and items are accessed using the square bracket symbols after variable name with an int or int variable within the square brackets. Items within the list are ordered, so unless the list is modified (removals, additions, swaps, etc.), the position of an item within the list will remain unchanged. For example, if you have the list [1, 2, 3], the value 1 will always be at index 0 until the list is modified.

Useful for:

  • Creating related groups of data
  • Keeping track of data without a known end point
  • Sorting data

List rules

1. Start and end the list sequence with an open ([) and closed (]) square bracket

2. Items in the list definition must be separated by commas

3. Items in the list can be variables of any data type, and can be implicitly or explicitly included

For example, we follow rule 1, 2, and 3 with the following list named a. The items in the list are implicit int definitions without defining any prior variables.

a = [10, 11, 12, 13]

print(a)
[10, 11, 12, 13]

You can also define int variables and then include those variables within the list. The previous example and the following example produce the exact same list.

b = 10
c = 11
d = 12
e = 13

a = [b, c, d, e]

print(a)
[10, 11, 12, 13]

Chapter 2.5.1 - List indexing

List items can be indexed just like string characters. The indexing rules remain the same (starting with 0, slicing, etc.).

The data type of a single index will be the same as the data type at that position.

In other words, if there is an int at that position, it can then be used just like an int

Example: access the 1st item in a and print it:

print(a[0])
10

We can also use an int variable to access this list item. The previous and next code examples are equivalent.

idx = 0

print(a[idx])
10

Add the 1st int to the 3rd int and print the result:

print(a[0] + a[2])
22

Chapter 2.5.2 - List operations

As was the case with strings, we can also access parts of a list using slicing. Also similar to strings, a sliced list will give you another list data type. This can be confusing when trying to access items (and their data type functionality) within the list. Specifically, the individual data types will not be accessible until you use a single index. This can result in unexpected behavior if you assume the slices can be treated as int.

the : operator

You can access multiple items and create a subset of a list by using the [start:finish] syntax that we used with strings. For example, you can print the items at indexes 0 and 1 at the same time, noting that the finishindex is not included.

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

print(slicing[0:2])
[1, 2]

You can implicitly create a subset from the start of the list to the finish index by providing no int before the :. The previous code example and the following code example are equivalent.

print(slicing[:2]) 
[1, 2]

Providing the start index and not the finish index will create a subset that goes from the starting index to the end of the list:

print(slicing[3:]) 
[4, 5, 6]

You can also access the middle of the list by providing a start and finish index at positions fully within the list.

print(slicing[1:4])
[2, 3, 4]

The sliced list can be set to a variable and treated like a list variable:

f = a[:2]

print(f[0])
10

The + operator

This operation does not behave as you might expect. It creates a new combined list from two different lists in the order they are placed in the operation (e.g., left list items first, right list items second). Without knowing this, you might assume the following code would print the sum of the sliced items at indexes 0 and 1 and the sliced items at indexes 2 and 3.

print(slicing[0:2] + slicing[2:4])
[1, 2, 3, 4]

What happened? If you reverse the order of the slices, it becomes more clear.

print(slicing[2:4] + slicing[0:2])
[3, 4, 1, 2]

As was the case with strings, you are only allowed to add a list to another list. If you try to add, for example, an int to a list, you will get an error:

print(slicing + 10)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[13], line 1
----> 1 print(slicing + 10)

TypeError: can only concatenate list (not "int") to list

The in and not in operators

The in operator provides a bool result where it is True if the item is in the list or False if it is not within the list. The not in operator provides the opposite results.

If you check to see if the int 5 is within the list, the result will be True since the list contains the int values [1, 2, 3, 4, 5, 6]. If you check to see if 5 is not in the list, it will result in False.

print(5 in slicing)

print(5 not in slicing)
True
False

We can try the opposite case:

print(10 in slicing)

print(10 not in slicing)
False
True

The * operator:

This operator adds a list to itself n times, where n is provided on the right side of the * operation:

[initial_list] * n

For example, the following two code examples are equivalent:

result_add = slicing + slicing + slicing # add slicing three times

result_mult = slicing * 3 # repeat slicing three times

print("code: slicing + slicing + slicing", result_add)

print("code: slicing * 3                ", result_mult)
code: slicing + slicing + slicing [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
code: slicing * 3                 [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]

Chapter 2.5.3 - List comprehension

Although list comprehensions fall under a more advanced concept named “looping”, this is a good time to introduce the functionality, in case you do want modify every item in your list (e.g., multiplication, addition, etc.). We will revisit this idea later in the class, but the code in the code cell below automatically does these tasks for you:

  1. visits each index in your list
  2. while at each index, it multiplies the value of the item at that index
  3. using rule #2 (Chapter 2.0.4) in variable definitions, modifying each index in the list would look like the following code if it were written out:
list_name = [1, 2, 3]
list_name[0] = list_name[0] * 10
list_name[1] = list_name[1] * 10
list_name[2] = list_name[2] * 10

print(list_name) #output: [10, 20, 30]

What is happening in the background? The mathematical operation first requires Python to access the value at the index. In this case, each value is an int. The int value is placed in the position of the indexed list item in the mathematical equation, where the code above is equivalent to the code below after replacement:

list_name = [1, 2, 3]
list_name[0] = 1 * 10 # the item at list_name[0] is 1 
list_name[1] = 2 * 10 # the item at list_name[1] is 2 
list_name[2] = 3 * 10 # the item at list_name[2] is 3

print(list_name) #output: [10, 20, 30]

Unlike strings, indexing items in a list allow you to access and/or change that value. In the examples above, the initial values are multiplied by 10, and then replaced by the result of that multiplication.

list_name = [1, 2, 3]

list_name = [item * 10 for item in list_name]

print(list_name)
[10, 20, 30]

Again, we will cover this process (i.e., looping) in great detail in future chapters.

Chapter 2.5.4 - List methods

As was the case with str, list data types have methods that can be used to access, modify, create, or delete items within the list.

Some commonly used list methods:

#1. append(): add a new item to the end of an existing list

a = [1, 2, 3]

a.append(4)

print(a)
[1, 2, 3, 4]

#2 sort(): sorts the list based on an alphanumeric order

b = [5, 1, 17, 0, 3]

b.sort()

print(b)
[0, 1, 3, 5, 17]

#3 len(): counts the number of items in the list

This is not a list method, per se, but is used very often with lists!

c = [100, 200, 300, 400, 500]

print(len(c))
5

Other functions:

insert: place an item at a specific index in a list

This function uses the following pattern to insert items in a list:

list_name.insert(index_to_insert, value_to_insert)

In the following example, the value 3 is inserted at index 2. This is equivalent to:

d = d[0:2] + [3] + d[2:]
d = [1, 2, 4, 5]

#d = d[0:2] + [3] + d[2:]
d.insert(2, 3)

print(d)
[1, 2, 3, 4, 5]

remove: removes the first item in the list that is equal to a given item

This function uses the following pattern to remove items in a list:

list_name.remove(value_to_remove)

In the following example, the first 2 is removed from the list:

e = [1, 2, 4, 2, 6]

e.remove(2)

print(e)
[1, 4, 2, 6]

pop: removes the last item from the list and provides the value for a variable definition

In the following example, the last item is removed from the list and set equal to the variable named pop_result

e = [1, 2, 4, 2, 6]

result = e.pop()

print("list after pop:", e)
print("'result' after pop:", result)
list after pop: [1, 2, 4, 2]
'result' after pop: 6

Chapter 2.5.5 - Practice

Provide code examples that answer the following questions using list indexing and/or slicing based on the list definition below:

D = [52, 55, 59, 62, 73, 44, 42, 41, 75]

What is the third int in D?

What is the int at the 6th index?

How would you access and print the first item in D?

How would I set a variable named t to the 8th int?

How would I output 86 using indexing and a print statement?

How would I add the item 20 to the end of the list defined below:

E = [52, 55, 59, 62, 73, 44, 42, 41, 75]

How would I sort the list defined below?

E = [52, 55, 59, 62, 73, 44, 42, 41, 75]

How would I find the number of items in the list below?

E = [52, 55, 59, 62]