Week 10

Lists

Author:Christopher Haynes
Email:chaynes@indiana.edu
Affiliation:Indiana University
Course:BL CSCI A201
Date:2008-03-20
Copyright © 2008, Christopher Haynes—all rights reserved.

Demo: Lists

>>> abc = list('abc')
>>> abc
['a', 'b', 'c']
>>> a1 = ['a', 1]
>>> a1
['a', 1]
>>> abc[1]
'b'
>>> abc[1:3]
['a', 'b']
>>> len(abc)
3
>>> abc + a1
['a', 'b', 'c', 'a', 1]
>>> abc * 2
['a', 'b', 'c', 'a', 'b', 'c']
>>> 'b' in abc
True
>>> 'd' in abc
False
>>> 'd' not in abc
True
>>> abc.find('b')
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'list' object has no attribute 'find'
>>> abc.index('b')
1
>>> abc.index('d')
Traceback (most recent call last):
  File "", line 1, in 
ValueError: list.index(x): x not in list
>>>
>>> abc_copy = abc[:]
>>> abc_copy
['a', 'b', 'c']
>>> a[1] = 2
>>> abc
['a', 2, 'c']
>>> abc[1:3]
[2, 'c']
>>> del abc[1]
['a', 'c']
>>> abc_copy
['a', 'b', 'c']
>>> abc.append('b')
>>> abc
['a', 'c', 'b']
>>> abc.append([3])
>>> abc
['a', 'c', 'b', [3]]
>>> abc[3].append(4)
>>> abc
['a', 'c', 'b', [3, 4]]
>>> not []
True

The list data type and how lists are like strings

List indexing picture

list.png


How lists are unlike strings

List mutation

Example: my_sum

def my_sum(lon):
    """
    Returns the sum of the given list of numbers.
    >>> my_sum([3, 1, 5])
    9
    >>>
    """
    # The built-in function sum is similar, but a little more general
    # Hint: use a counted accumulating loop
    answer = 0
    index = 0
    while index < len(lon):
        answer = answer + lon[index]
        index = index + 1
    return answer

clicker What is the value of [1,2][1]?

  1. 2
  2. [2]
  3. [1,2,1]
  4. [1]
  5. syntax error
  6. runtime error
  7. none of the above

Answer: A

clicker What is the value of [1,2] + [1]?

  1. 3
  2. [2]
  3. [1,2,1]
  4. [1]
  5. syntax error
  6. runtime error
  7. none of the above

Answer: C

clicker What is printed?

lst = [1]
lst = lst + 2
print lst
  1. [1, 2]
  2. [1, [2]]
  3. 3
  4. syntax error
  5. runtime error

Answer: E

clicker What is printed?

lst = [1]
lst + [2]
print lst
  1. [1]
  2. [1, [2]]
  3. [1, 2]
  4. syntax error
  5. runtime error

Answer: A

clicker What is printed?

lst = [1]
lst = lst + [2]
print lst
  1. [1]
  2. [1, [2]]
  3. [1, 2]
  4. syntax error
  5. runtime error

Answer: C

clicker What is printed?

lst = [1]
lst.append(2)
print lst
  1. [1, 2]
  2. [1, [2]]
  3. 3
  4. syntax error
  5. runtime error

Answer: A

clicker What is printed?

lst = [1]
lst.append([2])
print lst
  1. [1, 2]
  2. [1, [2]]
  3. 3
  4. syntax error
  5. runtime error

Answer: B

clicker What is the value of the expression?

([].append((3))[0]

  1. [3]
  2. 3
  3. 0
  4. syntax error
  5. runtime error

Answer: D

clicker What is the value of the expression?

[].append(3)[0] + [1]

  1. [3]
  2. 3
  3. 0
  4. syntax error
  5. runtime error

Answer: E

Exercise: concatenate_strings

def concatenate_strings(los):
    """
    Return the result of concatenating all the strings in the given list of
    strings.
    >>> concatenate_strings(['spam', 'eggs'])
    'spameggs'
    >>>
    """
    # The same result may be obtained using the empty string join method,
    # as in ''.join(los)
    #.
    #.
    #.
    #.
    #.
    #.

Solution: concatenate_strings

def concatenate_strings(los):
    """
    Return the result of concatenating all the strings in the given list of
    strings.
    >>> concatenate_strings(['spam', 'eggs'])
    'spameggs'
    >>>
    """
    # The same result may be obtained using the empty string join method,
    # as in ''.join(los)
    answer = ''
    index = 0
    while index < len(los):
        answer = answer + los[index]
        index = index + 1
    return answer

Exercise: rfind

def rfind(lst, value):
    """
    Return the index of the right-most occurrence of the value
    in the list, or -1 if there is no occurrence of the value.
    >>> rfind(['a', 3, 'b'], 3)
    1
    >>> rfind(['a', 3, 'b'], 'c')
    -1
    >>>
    """
    # Hint: loop backwards (use an indexed loop that decrements the index)
    #.
    #.
    #.
    #.
    #.
    #.

Solution: rfind

def rfind(lst, value):
    """
    Return the index of the right-most occurrence of the value
    in the list, or -1 if there is no occurrence of the value.
    >>> rfind(['a', 3, 'b'], 3)
    1
    >>> rfind(['a', 3, 'b'], 'c')
    -1
    >>>
    """
    # Hint: loop backwards (use an indexed loop that decrements the index)
    index = len(lst) - 1
    while index >= 0:
        if lst[index] == value:
            return index
        index = index - 1
    return -1

Appending to a list

Exercise: my_range

def my_range(n):
    """
    Return a list of the numbers 0, 1, ..., n-1.
    >>> my_range(4)
    [0, 1, 2, 3]
    >>>
    """
    # This is the same as the built-in function range with one argument
    #.
    #.
    #.
    #.
    #.
    #.

Solution: my_range

def my_range(n):
    """
    Return a list of the numbers 0, 1, ..., n-1.
    >>> my_range(4)
    [0, 1, 2, 3]
    >>>
    """
    # This is the same as the built-in function range with one argument
    answer = []
    count = 0
    while count < n:
        answer.append(count)
        count = count + 1
    return answer

Elementwise operations

Exercise: add_lists

def add_lists(lst1, lst2):
    """
    Return the result of adding the given lists elementwise.
    >>> add_lists([1, 2], [3, 4])
    [4, 6]
    >>>
    """
    # Hint: use an indexed accumulating loop and the list method append
    #.
    #.
    #.
    #.
    #.
    #.

Solution: add_lists

def add_lists(lst1, lst2):
    """
    Return the result of adding the given lists elementwise.
    >>> add_lists([1, 2], [3, 4])
    [4, 6]
    >>>
    """
    # Hint: use an indexed accumulating loop and the list method append
    index = 0
    answer = []
    while index < len(lst1):
        answer.append(lst1[index] + lst2[index])
        index = index + 1
    return answer

Mutation example: extend_list

def extend_list(extended_list, appended_list):
    """
    Extend extended_list by appending the elements in appended_list.
    Return None.
    >>> a = range(3)
    >>> b = list('abc')
    >>> extend_list(a, b)
    >>> a
    [0, 1, 2, 'a', 'b', 'c']
    >>>
    """
    index = 0
    while index < len(appended_list):
        extended_list.append(appended_list[index])
        index = index + 1

Example: concatenate_lists

def concatenate_lists(lst1, lst2):
    """
    Return a new list obtained by concatenating the elements of lst1 and
    lst2.
    >>> a = range(3)
    >>> b = list('abc')
    >>> concatenate_lists(a, b)
    [0, 1, 2, 'a', 'b', 'c']
    >>> a
    [0, 1, 2]
    >>>
    """
    return lst1 + lst2

Do not mutate a given list unless told to do so!

Exercise: elementwise_add_to_list

def elementwise_add_to_list(lst1, lst2):
    """
    Replace each value in lst1 with the result of adding to it
    the corresponding value in lst2.
    >>> lst = [1, 2]
    >>> elementwise_add_to_list(lst, [3, 4])
    >>> lst
    [4, 6]
    >>>
    """
    #.
    #.
    #.
    #.

Solution: elementwise_add_to_list

def elementwise_add_to_list(lst1, lst2):
    """
    Replace each value in lst1 with the result of adding to it
    the corresponding value in lst2.
    >>> lst = [1, 2]
    >>> elementwise_add_to_list(lst, [3, 4])
    >>> lst
    [4, 6]
    >>>
    """
    index = 0
    while index < len(lst1):
        lst1[index] = lst1[index] + lst2[index]
        index = index + 1