Tuples
Tuples
What does
immutable
mean?
www.umbc.edu
The Tuple Data Structure
• Each value in the tuple is an element or
item
• Elements can be any Python data type
– Tuples can mix data types
– Elements can be nested tuples
numbers = (1, 2, 3, 4)
print (numbers)
(1, 2, 3, 4)
www.umbc.edu
Creating Tuples
t2 = ('a',)
print (t2, type(t2))
www.umbc.edu
Creating Tuples
t3 = tuple('a',)
print (t3, type(t3)) ('a',) <class 'tuple'>
empty = tuple() ()
print (empty)
www.umbc.edu
Creating Tuples
aList = [1, 2, 3, 4]
aTuple = tuple(aList) What does this
print (aTuple) output?
(1, 2, 3, 4)
aStr = 'parrot'
('p', 'a', 'r', 'r', 'o', 't')
aTuple2 = tuple(aStr)
print (aTuple2)
www.umbc.edu
Indexing and Slicing Tuples
Tuple Indexing
• Just like other sequences (strings),
elements within a tuple are indexed
cheeses = ('swiss', 'cheddar',
'ricotta', 'gouda')
print (cheeses[0])
What does this
cheeses[0] = 'swiss' do?
Tuples are immutable.
www.umbc.edu
Slicing a Tuple
• Like other sequences, tuples can be sliced
• Slicing a tuple creates a new tuple. It does
not change the original tuple.
cheeses = ('swiss', 'cheddar',
'ricotta', 'gouda')
print (cheeses[1:4])
What does this
output?
('cheddar', 'ricotta', 'gouda')
www.umbc.edu
Tuple Operations
Operations on Tuples
• Tuples support all the standard sequence
operations, including:
– Membership tests (using the in keyword)
– Comparison (element-wise)
– Iteration (e.g., in a for loop)
– Concatenation and repetition
– The len() function
– The min() and max() functions
www.umbc.edu
Membership Tests (in)
• In Python, the in keyword is used to test if
a sequence (list, tuple, string etc.) contains
a value.
– Returns True or False
www.umbc.edu
Iteration
t = [('a', 0), ('b', 1), ('c', 2)]
for letter, number in t:
print (number, letter) Notice list of
tuples
1 b
2 c
www.umbc.edu
Concatenation (+)
• The + operator returns a new tuple that is a
concatenation of two tuples
a = (1, 2, 3)
b = (4, 5, 6)
What does this
c = a + b output?
print (a, b, c)
a = (1, 2, 3)
b = (4, 5, 6) What does this
output?
print (a*2, b)
(1, 2, 3, 1, 2, 3) (4, 5, 6)
www.umbc.edu
len() Functions
• The method len() returns the number of
elements in the tuple.
tuple0 = ()
print(len(tuple0))
tupleA = ("UMBC", "is", "the", "best")
print(len(tupleA))
What does this
0 output?
4
www.umbc.edu
min() and max() Functions
• max(tuple)
– Returns item from the tuple with max value
• min(tuple)
– Returns item from the tuple with min value
www.umbc.edu
Tuples and Functions
(return)
Tuples and functions
• Python functions (as is true of most
languages) can only return one value
– But… but… we’ve returned multiple values
before!
• If multiple objects are packaged together
into a tuple, then the function can return
the objects as a single tuple
www.umbc.edu
Example: min_max.py
# Returns the smallest and largest
# elements of a sequence as a tuple
def min_max(t):
return min(t), max(t)