BYU logo Computer Science

Python lists and tuples

Following is a summary of Python lists and tuples. Note, this material may be covered in a different order in class.

Lists

A list is a variable that references multiple values:

names = ['Maria', 'Mariano', 'Anna', 'Antonino']
numbers = [5, 8, 10, 13, 42]

A list can be empty:

good_recipes_for_brussel_sprouts = []

Length

You can get the length of a list with len():

number_of_names = len(names)

Appending to a list

One of the many functions we can perform on a list is appending items to it. This means adding items to the end of the list. For example:

pets = ['cat', 'horse', 'dog']
pets.append('emu')

Iterating over a list

for pet in pets:
    print(f'A {pet} is a good pet')

Indexing in a list

Taught in Unit 4

You can use square brackets to get a single element from a list:

names = ['Maria', 'Mariano', 'Anna', 'Antonino']
print(f'{names[2]} is my grandmother and {names[0]} is my aunt')

Indexing a list starts at zero.

List patterns

There are a few patterns of working with lists that are handy to remember:

  • map — create a new list that has the same number of items as the original list, with each item in the original list mapped to an item in the new list
  • filter — create a new list that has only some of the items of the original list
  • select — choose a single value from the list
  • accumulate — add or subtract the values in a list

Map pattern

Here is an example of the map pattern, where every word in the original list is replaced in the new list with a word that appends ‘room’ to it:

def make_rooms(words):
    rooms = []
    for word in words:
        room = word + 'room'
        rooms.append(room)
    return rooms


if __name__ == '__main__':
    some_words = ['ball', 'bath', 'bed', 'family', 'food', 'car']
    rooms = make_rooms(some_words)
    print(f'Original words: {some_words}')
    print(f'Rooms: {rooms}')

Filter pattern

Here is an example of the filter pattern, where every number in the original is kept in the new list only if it is an odd number.

def only_odds(numbers):
    odds = []
    for number in numbers:
        if (number % 2) == 1:
            odds.append(number)
    return odds


if __name__ == '__main__':
    print(only_odds([1, 2, 3, 4, 5, 6]))

Select pattern

Here is an example of the select pattern, where the we find the minimum value of a list of numbers:

def find_min(numbers):
    smallest = None
    for number in numbers:
        if smallest is None or number < smallest:
            smallest = number
    return smallest


if __name__ == '__main__':
    print(find_min([3, 6, 2, 8, 1, 7]))

Accumulate pattern

Here is an example of the accumulate pattern, where we find the average value of a list of numbers:

def average(numbers):
    total = 0
    for number in numbers:
        total = total + number
    return total / len(numbers)


if __name__ == '__main__':
    print(average([1, 2, 3, 4]))

Tuples

A tuple is a collection of one or more values, designated with parentheses:

student = ('Emma Johns', 22, 'political science')

In this case, the values might represent a student’s name, age, and major.

A tuple is not mutable (changeable). In other words, it is immutable (not changeable). Once you create a tuple, you can’t add anything to it or change its values.

Unpacking

You can unpack a tuple, which takes each of the parts of the tuple and stores them in separate variables:

name, age, major = ('Emma Johns', 22, 'political science')
print(f'{name} is {age} years old and a {major} major')

We now have three separate variables, name, age, and major instead of just student. We can print those using a formatted string.

Returning multiple values

Tuples are particularly helpful for returning multiple values from a function. This function sorts two values, a and b, returning the values in sorted order:

def sorted_order(a, b):
    """Return a and b in ascending order"""
    if a < b:
        return a, b
    else:
        return b, a


if __name__ == '__main__':
    first, second = sorted_order(4, 2)
    print(f'First comes {first}, then comes {second}')

Indexing a tuple

Taught in Unit 4

You can index a tuple just like a list:

student = ('Emma Johns', 22, 'political science')
name = student[0]

This is usually not as helpful as unpacking:

name, age, major = ('Emma Johns', 22, 'political science')

Tuples vs lists

It’s important to recognize that lists and tuples fill different roles.

listtuple
Can add or remove itemsImmutable
Size dynamically determined as the program runsSize fixed once it is created
Typically stores items of the same typeOften stores items of different types
The items are usually independent of each otherThe items usually go together as a unit of information
Typically processed with iterationTypically processed by unpacking

You typically want to use a list when you are working with a list of things that are all the same type and you don’t know how many items you will have until you run the program

You typically want to use a tuple when you are returning several values from a function or if you know in advance exactly how many items how will have (and this never changes)