You are on page 1of 24

Introduction

Fundamentals
Stacks, queres and matrices
Iterations
Summary

Lesson 2.4
Lists

ITC Faculty of Geo-Information Science and Earth Observation


University of Twente

2010

2.4 Lists page 1 of 24


Introduction
Objectives
Fundamentals
Structure
Stacks, queres and matrices Introduction
Expected results
Iterations
Prerequisites
Summary

Objectives

This lecture has three main objectives:


To demonstrate the use and syntax of the list datatype
To illustrate the use of various list methods.
To demonstrate sequential and iterative data processing on lists.

2.4 Lists page 2 of 24


Introduction
Objectives
Fundamentals
Structure
Stacks, queres and matrices Introduction
Expected results
Iterations
Prerequisites
Summary

Structure

This lecture is structured into the following six parts, including this
introduction:
Introduction
Basics
Stacks, queries, Matrices
Iterations
Lists are objects
Summary

2.4 Lists page 3 of 24


Introduction
Objectives
Fundamentals
Structure
Stacks, queres and matrices Introduction
Expected results
Iterations
Prerequisites
Summary

Expected results

At the end of this lecture you are expected:


To understand and be able to use list indexes
To be able to use lists for sequential and iterative data processing
Use lists as matrix data type (workaround)
Know the difference between a clone and a reference

2.4 Lists page 4 of 24


Introduction
Objectives
Fundamentals
Structure
Stacks, queres and matrices Introduction
Expected results
Iterations
Prerequisites
Summary

Prerequisites

Lesson 1.2 - Variables, expressions and statements


Lesson 1.3 - Functions
Lesson 1.4 - Conditionals and recursion
Lesson 2.2 - Iterations
Lesson 2.3 - Strings

2.4 Lists page 5 of 24


Introduction
Basics
Fundamentals
Lists Indexes
Stacks, queres and matrices
Methods Keywords
Iterations
Nested Lists
Summary

Lists [...]

We have already seen that Python knows a number of compound data


types. The most versatile of these is the list, which can be written as a set
of comma-separated values (items) between square brackets.

>>> a = ['spam', 'eggs', 100, 1234]

>>> a
['spam', 'eggs', 100, 1234]

The items need not all have the same type. Notice that the list above
contains a mix of strings and integers.

2.4 Lists page 6 of 24


Introduction
Basics
Fundamentals
Lists Indexes
Stacks, queres and matrices
Methods Keywords
Iterations
Nested Lists
Summary

List index

>>> a = ['spam', 'eggs', 100, 1234]


>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 2*a[:3] + ['Boo!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']

Like a string index, a list index always starts at 0. Just like strings, lists
can also be sliced, concatenated and so on.

2.4 Lists page 7 of 24


Introduction
Basics
Fundamentals
Lists Indexes
Stacks, queres and matrices
Methods Keywords
Iterations
Nested Lists
Summary

Negative indices

A list index can also have a negative value. A useful way to envisage this
is that there are in fact two ‘mirror’ copies of any list:

[ ' spam ' , ' eggs ' , ' bacon ' ][ ' spam ' , ' eggs ' , ' bacon ' ]
-3 -2 -1 0 1 2

Unlike strings, which are immutable, it is possible to change individual


elements of a list using its index:

>>> a
['spam', 'eggs', 100, 1234]

>>> a[2] = a[2] + 23

>>> a
['spam', 'eggs', 123, 1234]

2.4 Lists page 8 of 24


Introduction
Basics
Fundamentals
Lists Indexes
Stacks, queres and matrices
Methods Keywords
Iterations
Nested Lists
Summary

List length

The built-in function len() also applies to lists:


>>> a
[123, 'bltch', 'xyz', 1234, 123, 'blch', 'xzy', 34]

>>> len(a)
8

We should note that it is also possible to get the length of individual list
elements. For example, what is the value of len(a[0])?
Empty lists are useful at the start of iterations when the result will be a
list.
>>> a = [ ] # create a list with no elements
>>> len(a)
0

>>> a = list()
>>> len(a)
0

2.4 Lists page 9 of 24


Introduction
Basics
Fundamentals
Lists Indexes
Stacks, queres and matrices
Methods Keywords
Iterations
Nested Lists
Summary

The in keyword

We can use the in keyword for lists the same way we do for strings to find
whether or not a list contains a certain value.

>>> x = [1, 2, 3, 4, 5]

>>> 1 in x
True

>>> 100 in x
False

2.4 Lists page 10 of 24


Introduction
Basics
Fundamentals
Lists Indexes
Stacks, queres and matrices
Methods Keywords
Iterations
Nested Lists
Summary

Nested lists

It is possible to nest lists (create lists containing other lists),


for example:

>>> q = [2, 3]
>>> p = [1, q, 4]

>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2

>>> p[1].append('xtra')
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q
[2, 3, 'xtra']

2.4 Lists page 11 of 24


Introduction
Fundamentals
Lists Overview
Stacks, queres and matrices
Methods Examples
Iterations
Summary

The list data type has many methods:

append(x) - Add an item to the end of the list.


extend(L) - Extend the list by appending all the items in the given list.
insert(i, x) - Insert an item at a given position.
remove(x) - Remove the first item from the list whose value is x.
index(x) - Return the index in the list of the first item whose value is x.
count(x) - Return the number of times x appears in the list.
sort() - Sort the items of the list, in place.
reverse() - Reverse the elements of the list, in place.

2.4 Lists page 12 of 24


Introduction
Fundamentals
Lists Overview
Stacks, queres and matrices
Methods Examples
Iterations
Summary

List examples

>>> a = [66.25, 333, 333, 1, 1234.5]


>>> print a.count(333), a.count(66.25), a.count('x') # Count elements
2 1 0
>>> a.append(333) # Add elements
>>> a.insert(2, -1)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333) # Find elements
1
>>> a.remove(333) # Remove elements
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse() # Reverse list
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort() # Sort list
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]

2.4 Lists page 13 of 24


Introduction
Fundamentals List as stack
Stacks, queres and matrices Lists as quere List as stack
Iterations Lists as matrices
Summary

The list as a stack

The list methods make it very easy to use a list as a stack, where the last
element added is the first element retrieved. This is known as “last-in,
first-out” or LIFO).
To add an item to the top of the stack, use the append() method. To
retrieve an item from the top of the stack, we use the pop() method without
an explicit index.

>>> stack = [3, 4, 5]


>>> stack.append(6)
>>> stack
[3, 4, 5, 6, ]
>>> stack.pop()
6
>>> stack
[3, 4, 5]
>>> stack.pop()
5
...

2.4 Lists page 14 of 24


Introduction
Fundamentals List as stack List as queue
Stacks, queres and matrices Lists as quere Example
Iterations Lists as matrices The del statement
Summary

List as queue

You can also use a list conveniently as a queue, where the first element
added is the first element retrieved. This is known as “first in, first out” or
FIFO).
To add an item to the back of the queue, use append(), and to retrieve an
item from the front of the queue, use pop(0) with 0 as the index.

>>> queue = [ " Eric " , " John " , " Michael " ] # The queue

>>> queue . append ( " Terry " ) # Terry joins the queue
>>> queue . append ( " Graham " ) # Graham joins the queue

>>> queue . pop ( 0 ) # Eric leaves the queue


'Eric'

>>> queue . pop ( 0 ) # John leaves the queue


'John'

>>> queue # This is the current queue


['Michael', 'Terry', 'Graham']

2.4 Lists page 15 of 24


Introduction
Fundamentals List as stack List as queue
Stacks, queres and matrices Lists as quere Example
Iterations Lists as matrices The del statement
Summary

Queue or FIFO

>>> queue = ["Eric", "John", "Michael"]


>>> queue.append("Terry")
>>> queue.append("Graham")
>>> queue.pop(0)
'Eric'
>>> queue.pop(0)
'John'

>>> queue
['Michael', 'Terry', 'Graham']

This is what the queue looks like:

Eric John Michael


Eric John Michael Terry
Eric John Michael Terry Graham
John Michael Terry Graham
Michael Terry Graham

2.4 Lists page 16 of 24


Introduction
Fundamentals List as stack List as queue
Stacks, queres and matrices Lists as quere Example
Iterations Lists as matrices The del statement
Summary

The del statement

The del statement offers a way to remove an item from a list given its index
instead of its value. It can also be used to remove slices from a list.
For example:

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]

>>> del a[0] # or a.remove(-1)


>>> a
[1, 66.25, 333, 333, 1234.5]

>>> del a[2:4] # remove a slice


>>> a
[1, 66.25, 1234.5]

In some cases there are even options, as in the remove() method. However
this will remove the first instance of the value in a list, not necessarily the
one you might want to remove. However it would work in this case.
Note we can also remove slices!

2.4 Lists page 17 of 24


Introduction
Fundamentals List as stack List as queue
Stacks, queres and matrices Lists as quere Example
Iterations Lists as matrices The del statement
Summary

Deleting variables

The del statement can also be used to delete entire variables:

>>> del a

Referencing the name a hereafter is an error (at least until another value
is assigned to it):

>>> a
NameError: name 'a' is not defined

In fact, the del statement is even more powerful than illustrated here, so be
careful when using it.

2.4 Lists page 18 of 24


Introduction
Fundamentals List as stack
Stacks, queres and matrices Lists as quere Lists as matrices
Iterations Lists as matrices
Summary

Lists as matrices

Earlier in this lecture it was said that lists were a very flexible datatype.
Suppose we wanted to work with matrices. We could create a list of lists:

>>> a=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

>>> a
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> a[0]
[1, 2, 3]

>>> a[0][0]
1
>>> a[0][1]
2
...

There is a Python module called NumPyshort for Numerical Python.


This adds a fast array facility to the Python language, very much like lists,
and with many useful functions for matrices. (http://numpy.scipy.org/).

2.4 Lists page 19 of 24


Introduction
Fundamentals List as stack
Stacks, queres and matrices Lists as quere Lists as matrices
Iterations Lists as matrices
Summary

Cloning a list

If we don’t want b to refer to the same list we need to make a copy or a


clone. A slice always makes a copy:

>>> a = [ 0, 1, 4, 9, 16, 25 ]

>>> b = a[:] # Make a copy of a

>>> a.append(36)
>>> a
[0, 1, 4, 9, 16, 25, 36]

>>> b
[0, 1, 4, 9, 16, 25]

2.4 Lists page 20 of 24


Introduction
Fundamentals
Stacks, queres and matrices Iterations WHILE loops and FOR loops
Iterations
Summary

Iterations on Lists

Using a while loop:

>>> l = [ 0, 1, 4, 9, 16, 25 ]
>>> i = 0
>>> while i < len(l):
print l[i],
i += 1

0 1 4 9 16 25

Using a for loop:

>>> l = [ 0, 1, 4, 9, 16, 25 ]
>>> for e in l:
print e,

0 1 4 9 16 25

2.4 Lists page 21 of 24


Introduction
Fundamentals
Stacks, queres and matrices Summary
Iterations
Summary

Summary on Lists

A List is a compound data structure


A List is a sequence made up of mutable elements. It is therefore both
powerful and versatile.
An index is used to indicate an element
Lists can be nested
In Python, Lists are objects
Lists can be cloned with [:]
Strings can be converted to Lists and back

2.4 Lists page 22 of 24


Introduction
Fundamentals
Stacks, queres and matrices Summary
Iterations
Summary

Related data types

Tuples (...)
Like a List, but immutable!
Sequence data type

Dictionaries {...}
Like a list, but uses key
Iterable, but not a sequence data type!

Sets set( [...] )


Like a List
Unique elements:

>>> a=[1, 66.25, 333, 333, 1234.5]

>>> set(a)
set([66.25, 1, 333, 1234.5])

2.4 Lists page 23 of 24


Introduction
Fundamentals
Stacks, queres and matrices Summary
Iterations
Summary

Follow up

Lesson 3.1 on Dictionaries

2.4 Lists page 24 of 24

You might also like