There will be many situations where we want to represent arbitrary
sized information in the world. For example, a shopping list, a
list of friends, a set of photos, a family tree, etc. Python has a
number of built-in data types that can be used to represent arbitrary
sized information. At this point in the course we introduce the
list
data type.
Here are some examples of lists:
>>>
[]
; the empty list
>>>
[1]
; a list containing the single integer 1
>>> ['a', 'b', 'c'] ; a list of three strings, 'a', 'b'
and 'c'
>>> loi = [1, 2, 3] + [4, 5]
>>> loi
[1, 2, 3, 4, 5]
[1,
2, 3]
followed by all the elements in [4, 5]
, while
maintaining their order in which they appear in their respective
lists. That new list is then assigned to loi
.
We present some additional examples below:>>> loi
[1]
>>> loi = loi + [-4]
>>> loi
[1, -4]
>>> loi = loi + [3]
>>> loi
[1, -4, 3]
>>> loi = loi + [0, 5]
>>> loi
[1, -4, 3, 0, 5]
>>> loi = [3, -5] + loi
[3, -5, 1, -4, 3, 0, 5]
Individual items in a list can be retrieved using the indexing
operator. Each position in the list has a corresponding index as
illustrated in the diagram below. The first is at index 0, the
second at index 1, etc. Python also supports negative
indexing. So, the item at index -1 is at the end of the list, the
one at index -2 is next-to-end, etc.
>>> loi = [5, -3, 4, 2, 7]
>>> loi[0]
5
>>> loi[3]
2
>>> loi[-1]
7
>>> loi[-3]
4
Python lists support slicing operations. In general, a slicing
operation is of the form [start:end:skip]
. This operation
produces a new list that consists of every skip
'th
item that lies between index start
(inclusive) and index end
(exclusive). Note that each of these arguments is optional.
If start
is omitted, we start at the beginning of the
list. If end
is omitted, we run to the end of the
list. If skip
is omitted, we skip no items.
Slicing operations are illustrated in the examples below:
>>> loi = [5, -3, 4, 2, 7]
>>> loi[1:4]
[-3, 4, 2]
>>> loi[:2]
[5, -3]
>>> loi[1:4:2]
[-3, 2]
You are now in a position to figure out how to get the first
item in a list, to get the rest of the list (i.e., everything
but the first item in the list) and how to construct a new
list by adding one list to another - first, rest and
cons should sound very familiar to you!