Lists

Today introduces an important step in expanding the complexity of programs that you can write. So far you have only been able to store one value at a time in a variable, and this has limited what we can do. The one exception was our Image Manipulation lab where we read in an entire image of pixels into a single "object" variable ... it hid the more complex data type from you.

A list is an object that stores a sequence of values, allowing you to easily store and alter lots of values at once. Today introduces the List object, its functions, and the special syntax that goes with it.

Reading: Chapter 8

Read Chapter 8 up to and including "Lists and Functions"

Today in Class

We will discuss and learn about:

You should be able to understand these programs.

Input any number of numbers and print them out sorted.

# Input numbers from the user
nums = list()
x = input()
while x != "DONE":
      nums.append(float(x))
      x = input()
# Sort and print
nums.sort()
for num in nums:
      print(num, end=' ')
print()

Input a sentence, split its words, and find the name "Mr. X"

# Input a sentence
words = list()
x = input("Gimme a sentence: ")
words = x.lower().split()
mr = words.index("mr.")
if mr >= 0:
      print("Found someone named Mr.", words[mr+1])
else:
      print("No misters!")

This one is a bit longer, so jump right to a working Web version here to try it out.

# Command tool to add integers to a list.
# Also allows printing the list (dump), counting how
# many times a number appears in the list, and replacing
# all occurrences of an int with another int.
nums = list()

command = input(": ")
while command != "exit":
  # add 4 to the list
  if command.startswith("add"):
    num = int(command[4:])
    nums.append(num)

  # "count 4" (counts the occurrences of 4 in the current list)
  elif command.startswith("count"):
    num = int(command[6:])
    count = 0
    for x in nums:
      if x == num:
        count = count + 1
    print(count)

  # "dump" (print the current list)
  elif command == "dump":
    for num in nums:
      print(num, end=' ')
    print()

  # "change 4 9" (change all occurrences of 4 to 9)
  elif command.startswith("change"):
    parts = command.split()
    old = int(parts[1])
    new = int(parts[2])

    print("Changing", old, "to", new)
    for i in range(len(nums)):
      if nums[i] == old:
        nums[i] = new

  else:
    print("Unknown command!")    
      
  # Get the next command
  command = input(": ")
  

Here is an example of the above program running:

: add 4
: add 2
: add 9
: add 6
: count 3
0
: count 2
1
: add 9
: add 9
: add 1
: count 9
3
: dump
4 2 9 6 9 9 1 
: change 9 11
Changing 9 to 11
: dump
4 2 11 6 11 11 1 
: count 11
3
: done
Unknown command!
: exit