Skip to content

Lists

Lists are one of the most fundamental objects in any programming language.

Defining a List

A list is defined by putting the items of the list, separated by commas, inside square brackets [ ]. We can select items from the list as follows. (Note: the first item in a python list is indexed by 0, not 1 as you may have expected.)

L=[1,2,"milk","cheese","new shoes"]
print(L)
print(L[4])
Output:
[1,2,"milk","cheese","new shoes"]
'new shoes'

Trying to return a value at an index that is out of range triggers an error.

L[5]
Output:
-----------------------------------------------------------------
IndexError                      Traceback (most recent call last)
<ipython-input-30-7d1d7a0424fb> in <module>
----> 1 L[5]

IndexError: list index out of range

Order matters in a list. If items are in different orders, then the lists are not equal.

We can also create a list by stating conditions we want the elements to satisfy. This usually requires starting with a bigger list, and either constructing a sublist, or constructing a new list.

[n for n in [1,2,3,4] if is_even(n)]   
# selects the even integers from [1,2,3,4]
Output:
[2,4]
[2*n+1 for n in [1,2,3,4]]   
# creates a new list of odd integers from the old list
Output:
[3,5,7,9]

List Operations: remove, append, etc.

L=[1,2,3]
L.remove(3)   # removes item 3 from L
L
Output:
[1,2]
L.append(4)   # adds item 4 to the end of list L
L
Output:
[1,2,4]
len(L)
Output:
3

Here are some more list operations. In each of the following L is used as the name of our list and the operation being described is typed in bold.

operation description
x in L True if item x is in list L, else False.
x not in L False if item x is in list L, else True.
L + S The concatenation of lists L and S.
n*L, or L*n n copies of list L concatenated.
L[i] ith entry of list L (first entry has index \(0\)).
L[i:j] slice of L from i up to, but not including j.
L[i:j:k] slice of L from i to j with step k.
len(L) length of list L.
min(L) smallest item in L.
max(L) largest item in L.
L.append(x) Add an item x to the end of the list L.
L.extend(S) Extend the list L by appending all the items in the given list S to the end of L
L.insert(i,x) Insert item x in position i of list L. For example, L.insert(0, x) inserts x at the front of the list, and L.insert(len(L), x) is equivalent to L.append(x).
L.remove(x) Remove the first item from the list whose value is x. It is an error if there is no such item.
L.pop(i) Remove the item at the given position in the list, and return it. If no index is specified,L.pop() removes and returns the last item in the list.
L.index(x) Return the index of the first occurrence of item x in the list. It is an error if there is no such item.
L.count(x) Return the total number of times item x appears in the list.
L.sort() Sort the items of the list, in place.
L.reverse() Reverse the elements of the list, in place.

Constructing Lists

Python already has some quick ways to build lists that we can use. The range function, range(a,b), creates an iterable object consisting of integers beginning with a and ending at b-1. Here we assume a is less than b. We can turn this into a list as follows.

list(range(11))   # list of integers from 0 to 10
Output: [0,1,2,3,4,5,6,7,8,9,10]

list(range(5,11))   # list of integers from 1 to 10
Output:
[5,6,7,8,9,10]
list(range(0,11,2))   # list of integers from 0 to 10, step size 2
Output:
[0, 2, 4, 6, 8, 10]

We can also convert a string into a list of characters.

list('hello world')
Output:
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

Similar to strings We can select one or multiple items from a list using slicing.

L=range(1,26)
print(L[1])      # selects item of index 1
print(L[0:3])   # sublist of L consisting of items indexed 0 through 2
Output:
2
[1,2,3]

The items in a list can be overwritten by new items (i.e. lists are mutable).

L=[1,2,3,4]
L
Output:
[1,2,3,4]
L[1]=5
L
Output:
[1,5,3,4]

An example of generating a list of squares.

[n**2 for n in range(1,11)]
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

🚧 UNDER CONSTRUCTION 🚧

Add info about mutable, and .deepcopy method and examples