Tuples and More Lists

Last time we learned about Lists, a very useful Python object. Today we add another Python object called the Tuple. On the surface they are very similar with some similar functionality. However, Tuples are not types of Lists, and Lists are not types of Tuples. A Tuple is called an immutable object (Lists are mutable) which means once you create it, you can't change it. You can't make it longer, and you can't change its elements. Today we'll talk about why that is useful, how to use tuples, and when is most appropriate to use them.

We will also cover a few miscellaneous items that make using Lists and Tuples a delight.

Reading: Chapter 10 (up to but stop before "Dictionaries and tuples")

You can jump to Chapter 10 here.

Today in Class

We will discuss and learn about:

You should be able to understand these programs.

This program lets the user type in anything, "My name is Samuel" or "It's Samuel" or "Well you want to know huh? Fine I'm Samuel", and it easily pulls the name off the end of the sentence.

# Input a full sentence from the user
sentence = input("What's your name? ")
words = sentence.split()
name = words[-1]
print("Hello", name, " nice to meet you!")

Here is a basic calculator to input things like "3 + 6 - 3 + 8 + 6 - 2 - 6 ="

cmd = input("calculator: ")
parts = cmd.split()

total = 0
addition = True
for x in parts[0:-1]:  # don't include the final = sign
    if x == '+':
        addition = True
    elif x == '-':
        addition = False
    else:
        if addition:
            total = total + int(x)
        else:
            total = total - int(x)

print("=", total)