lists (slides)

CSc 110 - Lists

Announcement

Review session tomorrow (Tuesday, Feb 18)

  • Location: Gittings 129b

  • Time: 5 - 7 : 00 pm

Sequences

We’ve worked with strings, which are sequences in Python. Sequences can be indexed with [ ]:

word = "lotion"
word[0] # returns first character in string
'l'
word[1] # returns second character in string
'o'

We also have lists in Python, which are also sequences and can indexed with [ ]:

numbers = ['l', 'o', 't', 'i', 'o', 'n']
numbers[0] # returns first item in list
'l'

Data Structures

  • Data structures is a way to organize data when coding
  • Data structures allow for easy access and modification of values
  • You can see data structures as a collection of data values
  • In Python lists are a data structure that is:
    • mutable (you can change the values in it)
    • unordered – you can have repeated elements in a list

Creating lists

# empty list
no_numbers = []

# list of integers
numbers = [1, 5, 2, 10, 7]

# list of strings
names = ['SZA', 'JVKE', 'Bruno Mars', 'Doechii']

# mixed types list
values = [2, 1.15, 7, 1.75, 'those']
print(values[0] * values[1])
2.3

Write a function

Its name is sum_all that takes a list of values as an argument. It runs a loop that iterates through the number in values summing all numbers. It returns the sum of all numbers in values. HINT: a) create a variable that accumulate the sum and b) use while.

Name your file sum_list.py and submit to Gradescope.

assert sum_all([2, 2, 2]) == 6
assert sum_all([2, 1, 5, 2, 3]) == 13
assert sum_all([]) == 0

Write a function – solution

def sum_all(values):
  total = 0
  index = 0
  while index < len(values):
    total += values[index]
    index += 1
  return total

def main():
  assert sum_all([2, 2, 2]) == 6
  assert sum_all([2, 1, 5, 2, 3]) == 13
  assert sum_all([]) == 0
    
main()

Loop Table

We start with index = 0 and total = 0:

sum_all([2, 1, 5, 2, 3])
index index < len(values) values[index] total
0 True 2 0 + 2 = 2
1 True 1 2 + 1 = 3
2 True 5 3 + 5 = 8
3 True 2 8 + 2 = 10
4 True 3 10 + 3 = 13
5 False - 13

Loop Table

Start with index = 0 and total = 0:

sum_all([2, 1, 3, 4])
index index < len(values) values[index] total
|
|
|
|
|
|

Loop Table – solution

sum_all([2, 1, 3, 4])
index index < len(numbers) numbers[index] total
0 True 2 2
1 True 1 3
2 True 3 6
3 True 4 10
4 False - 10

Python Tutor

You can also visualize code in python on Python Tutor

Using a control variable

Remember how to get the max of three numbers?

def max3(x, y, z):
  max = x # assume max is first number
  if y > max:
    max = y # assumption is incorrect, assume y is max
  if z > max:
    max = z # assumption is incorrect, z is max
  return max

def main():
  print( max3(1, 2, 2) ) # 2
  
main()
2

Adapt this function (max_list) to take a list of numbers (for example [1, 2, 2, 1, 3, 1, 1]) instead of three numbers (use while).

Max of list – solution

def max_list(numbers):
  '''
  Given a list of number, this function returns the highest number.
  Args:
    List of numeric values
  Returns:
    Max (float or integer, whatever value type is the highest)
  '''
  max = numbers[0]
  index = 1
  while index < len(numbers):
    if numbers[index] > max:
      max = numbers[index]
    index += 1
  return max

def main():
  print( max_list([1, 2, 2, 1, 3, 1, 1]) ) # 3
  print( max_list([3, 2, 2, 1, 0, 1, 1]) ) # 3
  
main()
3
3

Loop table

We start with index = 1 and max = 2:

max_list([2, 1, 3, 1])
index index < len(numbers) numbers[index] max
|
|
|
|
|
|

Loop table – solution

We start with index = 1 and max = 2:

max_list([2, 1, 3, 1])
index index < len(numbers) numbers[index] max
1 True 1 2
2 True 3 3
3 True 1 3
4 False - 3

Max solution

  • What about empty lists?
  • How to get the min instead?
assert max_list([]) == None
assert max_list([2, 1, 3, 1]) == 3

Max solution - empty lists

Can we swap the two expressions at line 5?

def max_list(numbers):
  max = None
  index = 0
  while index < len(numbers):
    if max == None or numbers[index] > max:
      max = numbers[index]
    index += 1
  return max

def main():
  print( max_list([2, 1, 3, 1]) ) # 3
  print( max_list([]) ) # None

main()
3
None

Updating lists

names = ['SZA', 'JVKE', 'Bruno Mars']

# mutate list using the index
names[1] = "Billie Eilish"

names
['SZA', 'Billie Eilish', 'Bruno Mars']

Write a function

Its name is double that takes a list of numeric variables as argument. It iterates over the list (use while) doubling (multiplying by two) each value in the list. It returns the modified list.

assert double([0, 1, 2, 3]) == [0, 2, 4, 6]

Write a function – solution

def double(numbers):
  index = 0
  while index < len(numbers):
    numbers[index] *= 2
    index += 1
  return numbers

def main():
  original_list = [0, 1, 2, 3]
  new_list = double(original_list)
  assert original_list == new_list
  assert original_list == [0, 2, 4, 6]
  
  print("Passed all tests")
  
main()

Slicing lists

  • Range – list[2:4]
  • Whole list – list[:]
  • Everything but last character – list[:-1]

The same slicing can be done with strings