Section 1: Lists

 Table of Contents > Chapter 2 > Section 1 

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. 


Constructing lists

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'

Lists can be added together to construct new lists.  So, for example, assuming that loi1 and loi2 are lists of integers, the statement:

>>> loi = [1, 2, 3] + [4, 5]
>>> loi
[1, 2, 3, 4, 5]

constructs a new list obtained by adding all the elements from [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]


Accessing items in a list

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. 

List indeces

Indexing operations are illustrated below:

>>> loi = [5, -3, 4, 2, 7]

>>> loi[0]

5

>>> loi[3]

2

>>> loi[-1]

7

>>> loi[-3]

4


Slicing operations

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!

Review 2.1: Working with lists

Question 1 of 3

Which of the following statements gets the first item in the list loi?
 
loi[1]

loi[0]