Hello World! An Invitation to Computer Science

Lecture Slides

Lists in Python
Monday April 14, 2008


Key ideas from last time


Lists: like strings, only more general


Membership: in and not in

a form of sequential search is primitive in Python:

  >>> my_list = [3, 1, 99, 8]
  >>> 99 in my_list
  True
  >>> 5 in my_list
  False
  >>> 5 not in my_list
  True


Ranges are lists

  >>> range(10)
  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  >>> range(1,5)
  [1, 2, 3, 4]
  >>> range(20, 1, -5)
  [20, 15, 10, 5]
  >>> range(3, 10, 2)
  [3, 5, 7, 9]

Mutability

>>> a = 'hello'
>>> a
'hello'
>>> b = a
>>> b
'hello'
>>> b = 'bye'
>>> b
'bye'
>>> a
'hello'

>>> my_list = [2, 9, 1]
>>> my_list
[2, 9, 1]
>>> your_list = my_list
>>> your_list
[2, 9, 1]
>>> your_list[2] = 63
>>> your_list
[2, 9, 63]
>>> my_list
[2, 9, 63]

Selection sort revisited

def find_largest(a_list, n):
  max_pos = 0
  i = 1
  while i < n:
      if a_list[i] > a_list[max_pos]:
          max_pos = i
      i += 1
  return max_pos


def exchange(a_list, i, j):
    temp = a_list[i]
    a_list[i] = a_list[j]
    a_list[j] = temp


def move_largest(a_list, n):
    max_pos = find_largest(a_list, n)
    if max_pos != n-1:
        exchange(a_list, max_pos, n-1)


def selection_sort(a_list):
    n = len(a_list)
    while n > 1:
        move_largest(a_list, n)
        n -= 1


>>> my_list = [17, 5, 94, 3, 1, 6]
>>> selection_sort(my_list)
>>> my_list
[1, 3, 5, 6, 17, 94]