Help hurricane victims by donating to the American Red Cross.

Chap2

From Ollie's Web Site

Contents

Chapter 2: Lists & Tuples

Data Structure: a collection of data elements that is structured in some way.

Container - any object that can contain other objects. Two main containers: 1 sequences (like lists and tuples) 1 mappings (such as dictionaries). When the elements of a sequence are numbered, each element in a mapping has a name, also called a key. Mappings are in Chapter 4. 1 sets, a container type that is neither a sequence nor a mapping. See Chapter 10.

Sequences

6 built-in types of sequences:

  • lists - you can change a list
  • tuples - you can't change a tuple.
  • strings
  • Unicode strings
  • buffer objects
  • xrange objects

Examples of lists:

>>> edward = ['Edward Gumby', 42]
>>> john = ['John Smith', 50]
>>> database = [edward, john]
>>> database
[['Edward Gumby', 42], ['John Smith', 50]]

Common Operations

  • Indexing
  • Slicing
  • Adding
  • Multiplying
  • Membership checking
  • Iteration - cover under Loops in Chapter 5.

Indexing

>>> greeting = 'Hello
>>> greeting[0]
'H'
>>> greeting[-1]
'o'
>>> 'Hello'[1]
'e'

If a function call returns a sequence, you can index it directly"

>>> fourth = raw_input)'Year: ')[3]
Year: 2005
>>> fourth
'5'

Slicing

Indexing accesses individual elements, while slicing accesses ranges of elements, e.g.,

>>> tag = '<a href="http://www.python.org">Python web site</a>'
>>> tag[9:30]
'http://www.python.org'
>>> tag[32:-4]
'Python web site'
>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[3:6]
'[4, 5, 6]'
>>> numbers[0:1]
'[1]'

The first number is the number to start the slice, while the 2nd is the number of the first element after the slice. The 1st number is inclusive, while the 2nd is exclusive.

If you want to slice to the end, leave out the 2nd number:

>>> numbers[-3:]
'[8, 9, 10]

The same works for the beginning:

>>> numbers[:3]
'[1, 2, 3]'

While leaving out both gives the whole sequence:

>>> numbers[:]
'[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'

Adding a 3rd parameter introduces the step size:

>>> numbers[3:6:3]
'[4]'
>>> numbers[:4]
'[1, 5, 9]'

Adding Sequences (Concatenation)

Same type!

>>> [1, 2, 3] + [4, 5, 6]
'[1, 2, 3, 4, 5, 6]'
>>> [1, 2, 3] + ['a', 'b', 'c']
(error message)

Multiplication

Multiplying a sequence by a number, n, repeats the sequence n-times.

>>> 'python' * 5
'pythonpythonpythonpythonpython'
>>> [42] * 5
'[42, 42, 42, 42, 42]'

None, Empty Lists and Initialization

Empty list: []

None: a python value for nothing.

Initialize a list with 10 empty elements:

>>> sequence = [None] * 10
'[None, None, None, None, None, None, None, None, None, None]'

Membership

The in operator tells whether an element is in a sequence.

>>> permissions = 'rw'
>>> 'w' in permissions
True
>>> 'x' in permissions
False
>>> users = ['qwe', 'owa', 'asd']
>>> raw_input('User: ') in users
User: owa
True

Some built-in functions

  • len(number) - returns the number of elements in number.
  • min(number) - returns the smallest element in number.
  • max(number) - returns the largest element in number.

List: Python's Workhorse

The list function

Converts a string to a list:

>>> list('Hello')
['H', 'e', 'l', 'l', 'o']

The 'join' function, q.v. Chapter 3 reverses the above.

Basic List Operations

This is how to change lists.

Item Assignments

>>> x = [1, 1, 1]
>>> x[1] = 2
>>> x
[1, 2, 1]

Extend

Like concatenation, but replaces the first list with the concatenated one.

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a.extend(b)
[1, 2, 3, 4, 5, 6]

which is logically equivalent (but more efficient than):

>>> a = a + b
[1, 2, 3, 4, 5, 6]

Index

Search a list and return the index value of the 1st hit.

>>> knights = ['We', 'are', 'the', 'knights', 'who', 'say', 'ni']
>>> knights.index('who')
4
>>> knights.index('qwer')
(error message)

Insert

>>> knights.insert(3, 'smarmy')
['We', 'are', 'the', 'smarmy', 'knights', 'who', 'say', 'ni']

pop

Removes an element, by default the last one.

>>> x = [1, 2, 3]
>>> x.pop()
3
>>> x
[1, 2]
>>> x.pop(0)
1
>>> x
[2]

This allows creating a LIFO stack. Use append to add an element to the stack, and pop to remove an element from the stack.

remove

Removes the 1st occurrance of a value.

>>> x = ['to', 'be', 'or', 'not', 'to', 'be']
>>> x.remove('be')
>>> x
['to', 'or', 'not', 'to', 'be']

reverse

Reverses the elements in the list.

>>> x = [1, 2, 3]
>>> x.reverse
>>> x
[3, 2, 1]

sort

Sorts lists in place.

>>> x = [4, 6, 2, 1, 7, 9]
>>> x.sort()
>>> x
[1, 2, 4, 6, 7, 9]

Note:

>>> x = [4, 6, 2, 1, 7, 9]
>>> y = x   # makes y and x refer to the same list
>>> x.sort()
>>> x
[1, 2, 4, 6, 7, 9]
>>> y
[1, 2, 4, 6, 7, 9]

while

>>> x = [4, 6, 2, 1, 7, 9]
>>> y = x[:]   # makes y = a copy of the list
>>> x.sort()
>>> x
[1, 2, 4, 6, 7, 9]
>>> y
[4, 6, 2, 1, 7, 9]

Another approach to the latter uses the sorted function:

>>> x = [4, 6, 2, 1, 7, 9]
>>> y = sorted(x)
>>> x
[4, 6, 2, 1, 7, 9]
>>> y
[1, 2, 4, 6, 7, 9]

More on sorting at Andrew Dalke's Sorting Mini-HOWTO

Tuples: Immutable Sequences

>>> 1, 2, 3         # this makes a tuple
(1, 2, 3)
>>> (1, 2, 3)       # as does this
(1, 2, 3)
>>> ()              # the empty tuple
()
>>> 42              # doesn't create a single-valued tuple
42
>>> 42,             # but this does
(42,)
>>> (42,)           # as does this
(42,)
>>> 3*(40+2)        # not a tuple
126
>>> 3*(40+2,)       # a tuple
(42, 42, 42)