Using tuplesSlide solved ✓
Tuples are generally used the same way as lists. The things you learned about lists apply to tuples, too.
Looping over a tuple
You can use a for loop to iterate over each item in a tuple:
for i in (1, 2, 3): print(i)
Try looping over a tuple
Loop over the tuple
coordinates below, printing each of its elements on a
You can use the
in keyword to check if an element is in a tuple. For
colors = ("red", "green", "blue") print("blue" in colors)
Try the in keyword
Write a function named
has_10 that takes a single parameter. The parameter
is a tuple. Return
True if the tuple contains the number
You use bracket notation to index into a tuple. For example:
colors = ("red", "green", "blue") print(colors)
Index into the
colors tuple to retrieve the third element, then print it.
Length of a tuple
You can use
len to compute the length of a tuple, just as with lists and
strings. For example:
len((1, 2, 3)) == 3
Try using len
The code below defines a list of tuples. Loop over each tuple in the list and prints the length of each tuple.
You can assign a tuple of values to a tuple of variables. For example:
(a, b) = (1, 2)
After that line, the
a variable will contain
1 and the
b variable will
With such assignments it is allowed to omit the parentheses. So we could have written:
a, b = (1, 2)
a, b = 1, 2
You can use tuple assignment to retrieve the elements in a tuple into separate variables. This is called to unpack the tuple.
For example, say that you are given this tuple:
coordinate = (12, 33)
You want to extract the two elements. You could say:
x = coordinate y = coordinate
But instead, you could write:
x, y = coordinate
to unpack the tuple. Doing it that way is more readable, shorter, and cleaner.
Try unpacking a tuple
add_coordinates below takes a single parameter that is a tuple
with two elements. Unpack the tuple into two variables,
using square brackets. Then return
x + y.
add_coordinates((1, 2)) == 3 add_coordinates((4, 4)) == 8
Returning multiple values
Sometimes it is useful to return more than one value from a function. You can use tuples to accomplish this. For example:
def get_colors(): color1 = "green" color2 = "blue" return color1, color2 c1, c2 = get_colors()
get_colors function returns a tuple with two items, and the assignment
c1, c2 is an assignment to a tuple of variables. In both cases we have
omitted the parentheses, since it looks cleaner.
Try returning multiple values
return statement to the function below so that it returns