Python Tuples

Question Click to View Answer

What does the following code print?

something = (1, "bob", True)
print(something)

(1, 'bob', True) is printed.

(1, 'bob', True) is referred to as a tuple. Tuples are ordered collections of items that are immutable. Tuples are similar to lists, but lists are mutable and tuples are immutable.

What does the following code print?

letters = ("a", "g", "f")
print(letters[1])

"g" is printed.

The letters tuple has three items. We use indexing to return the item in position 1 of the tuple. Tuples are ordered collections so indexing can be used.

Remember that unordered connections like dictionaries and sets cannot be indexed.

What does the following code print?

letters = ("a", "g", "f")
print(letters[-1])

"f" is printed.

Negative indexing can be used to fetch items from the end of the tuple. -1 is the last position in the tuple, -2 is the second to last position in the tuple, and so forth.

What does the following code print?

clothes = ("sock", "belt", "hat")
clothes[0] = "pants"
print(clothes)

This code raises a TypeError with the following message: 'tuple' object does not support item assignment.

Tuples are immutable so items in a tuple cannot be replaced.

What does the following code print?

t1 = ("a",)
t2 = ("b",)
t3 = t1 + t2
print(t3)

('a', 'b') is printed.

The + operator performs concatenation when both the operands are tuples. The + operator returns a new tuple - it doesn't modify t1 or t2. Tuples are immutable and cannot be modified.

Single element tuples like t1 and t2 must be defined with a trailing comma to differentiate them from normal strings.

What does the following code print?

phones = ("iphone", "samsung", "iphone")
print(phones.count("iphone"))

2 is printed.

The count() method returns the number of times an item is present in a tuple.

What does the following code print?

heaters = ("oven", "stove")
print("microwave" in heaters)

False is printed.

The in operator returns False if the left operand is not present in the tuple. "microwave" is not in the heaters tuple.

What does the following code print?

happy_stuff = ("smile", "laugh", "sing")
for word in happy_stuff:
    print(f"I like to {word}")

The following lines are printed:

I like to smile
I like to laugh
I like to sing

for loops can be used to iterate over every item in a tuple.

What does the following code print?

print(any((False, False, False)))

False is printed.

any() returns False when all the tuple items are False.

What does the following code print?

print(any((False, True, False)))

True is printed.

any() returns True when one of more of the tuple items are True.

What does the following code print?

print(min((90, 4, 88)))

4 is printed.

The min() method takes a tuple as an argument and returns the smallest item in the tuple.