You are on page 1of 5

1/12/23, 1:55 PM PYCS 07 - Tuples - Colaboratory

A Python Introduction for New (and not-so-new)


Programmers
Part 07: Keeping Track of Stuff with Tuples

This Python Notebook is part of a sequence authored by Timothy R James - feel free to modify, copy,
share, or use for your own purposes.

Now that we have learned a bit about loops, we can apply that knowledge to a new topic: tuples.

Tuples in Python

A tuple is a structure that we can use in Python to keep track of groups of things. We've already
seen float, int, string, and boolean types; a tuple is a new type that can contain any of these. We
declare a tuple using parentheses - the ( and ) characters, and we separate the different
elements of the tuple with commas.

For example, here's how we declare a tuple containing the numbers 1, 2, and 3.

my_tuple = (1, 2, 3)

You can print it just like you would any other variable. It'll show you what the list contains.

my_tuple = (1, 2, 3)

print(my_tuple)

You can also have a tuple full of boolean values:

booleans = (True, False, False, False, True)

You could have a tuple full of strings, too:

fruits = ('apples', 'bananas', 'cherries')

https://colab.research.google.com/drive/149X-6CJl7kJc8SZOx5PQHlQyU0eQuyJ2?usp=sharing#printMode=true 1/5
1/12/23, 1:55 PM PYCS 07 - Tuples - Colaboratory

Tuples don't have to contain only the same kind of thing - the type of each value in a tuple can be
mixed. See below; one tuple can easily contain an int, a string, a float, and a boolean.

things = (7, 'thing', 3.7, True)

print(things)

In fact, tuples can even contain other tuples.

list_list = ((1, 2, 3), (4.0, 5.0, 6.0), (True, False))

print(list_list)

Accessing the Values in a Tuple

Once we have a tuple, we can access each individual element in the tuple using an index. To
access one element, we use the variable for the tuple, followed by a square bracket ( [ ), followed
by the index (which is just a number), followed by another square bracket ( ] ). Note that the first
index in the tuple is 0 , not 1 .

This code should give you some idea.

fruits = ('apples', 'bananas', 'cherries')

first_value = fruits[0] # remember, lists start with 0, not 1

second_value = fruits[1]

third_value = fruits[2]

print('The first value is %s.' % first_value)

print('The third value is %s.' % third_value)

In fact, tuples give us a really great capability - now we can combine multiple values in a string
using % and a tuple, like this:

fruits = ('apples', 'bananas', 'cherries')

first_value = fruits[0]

third_value = fruits[2]

print('Last is %s and first is %s.' % (third_value, first_value))

Note that you don't have to use a number literal as an index, you can also use a variable.

https://colab.research.google.com/drive/149X-6CJl7kJc8SZOx5PQHlQyU0eQuyJ2?usp=sharing#printMode=true 2/5
1/12/23, 1:55 PM PYCS 07 - Tuples - Colaboratory

fruits = ('apples', 'bananas', 'cherries')

first_index = 0

print(fruits[first_index])

Finding the Length of a Tuple

We can figure out the number of items in a tuple by just looking at it and counting them.

fruits = ('apples', 'bananas', 'cherries', 'dates', 'elderberries', 'figs')

number_of_fruits = 6 # 1, 2, 3, 4 is dates, 5, 6 is figs. There are 6 of them.

print('We have ' + str(number_of_fruits) + ' fruits.')

The problem is, what if we add a fruit to fruits ? Or remove one? Now we have to remember to
change number_of_fruits too, and we might make a mistake - or forget to update it. This is the
kind of thing we typically like to avoid, but there's an easy solution.

We can use len() to find the length of a tuple. While we can count the number of items in a tuple
manually, it's simpler to be able to use this in our code. This helps us to avoid mistakes.

fruits = ('apples', 'bananas', 'cherries', 'dates', 'elderberries', 'figs')

number_of_fruits = len(fruits)

print('There are %s fruits.' % number_of_fruits)

The other nice thing about len() is that it works with a whole bunch of things in Python, including
strings!

fruits = ('apples', 'bananas', 'cherries', 'dates', 'elderberries', 'figs')

number_of_fruits = len(fruits)

number_of_letters_in_apples = len(fruits[0])

print('There are %s letters in %s.' % (number_of_letters_in_apples, fruits[0]))

Iteration with Tuples

Using len() along with a while loop, we could print out each fruit on its own line.

fruits = ('apples', 'bananas', 'cherries', 'dates', 'elderberries', 'figs')

counter = 0

https://colab.research.google.com/drive/149X-6CJl7kJc8SZOx5PQHlQyU0eQuyJ2?usp=sharing#printMode=true 3/5
1/12/23, 1:55 PM PYCS 07 - Tuples - Colaboratory

while counter < len(fruits):

    print('Fruit %s is %s.' % (counter, fruits[counter]))

    counter += 1

print("That's all the fruits!")

We could also tell the user how many letters are in each of the fruits.

fruits = ('apples', 'bananas', 'cherries', 'dates', 'elderberries', 'figs')

counter = 0

while counter < len(fruits):

    print('%s has %s letters.' % (fruits[counter], len(fruits[counter])))

    counter += 1

We can use a tuple and a while loop to easily sum numbers.

numbers = (9, 11, 31, 40, 55, 63, 68, 81, 90)

sum = 0

i = 0 # i is not usually the best name for a variable, but it's common for this.

while i < len(numbers):

    sum += numbers[i]

    i += 1

print('The sum of %s is %s.' % (numbers, sum))

You Try It!

Create a tuple below with your 5 favorite games or sports. Print your third favorite.

games = ()

For the tuple below, can you write code that will use a loop to count the positive and negative
numbers, and output both counts?

numbers = (86, -62, -98, 31, 87, 93, 99, 11, 47, 34, -18, -97, 74, 91, 6, 44)

positives = 0

negatives = 0

https://colab.research.google.com/drive/149X-6CJl7kJc8SZOx5PQHlQyU0eQuyJ2?usp=sharing#printMode=true 4/5
1/12/23, 1:55 PM PYCS 07 - Tuples - Colaboratory

# your code here

Colab paid products


-
Cancel contracts here

https://colab.research.google.com/drive/149X-6CJl7kJc8SZOx5PQHlQyU0eQuyJ2?usp=sharing#printMode=true 5/5

You might also like