Tuples
Introduction to Computer Programming CSCI-UA.0002-001
Sequence Types
We know two sequence types. What are they?
How Are Strings and Lists Similar?
Sequence types support a number of operations…
Name some operations or functions that can be used on both strings and lists.
What does the operation do, and what does it return for each type?
Sequence Operations and Functions
+ concatenation - adds all of the elements from one sequence to another; returns a new sequence
* multiplication - repeats a sequence for the specified number of times; returns a new sequence
[i] indexing - retrieves the element at the specified index; returns the value
[m:n] slicing - retrieves a subsequence; returns a new sequence
len() length - returns the length of the sequence
for… in iteration - traverses over every element of sequence
in/not in membership - tests if values is in sequence
But Strings and Lists Are Different!
How are strings and lists different?
a string is an ordered sequence of characters…
a list is an ordered sequence of values (any values)…
But there's also another big difference.
strings are immutable
lists are mutable
A Third Sequence Type
Surely you must be thinking: I really wish that my list was not mutable
(well… probably not… but…)
Tuples
A tuple is an immutable grouping of data. Think of it as an immutable list.
just like a list, it can hold heterogeneous values
it can hold strs, lists, ints, and even other tuples
however, it can't be changed!
you can't add items (no extend or append)
you can't remove items (no remove; del doesn't work)
you can't change items (assignment doesn't work)
Tuple Syntax
A tuple is really just a group of comma separated values. A tuple literal is just values and commas. Really! (btw, chugs exist, and are a thing )
>>> dogs = "chihuahua", "pug", "chug"
>>> print(dogs)
('chihuahua', 'pug', 'chug')
However… it's common to put parentheses around a tuple (in fact, when you print a tuple, parentheses are always placed around it).(apparently Pelicans is now the name of a professional basketball team !)
>>> birds = ("pelican", "owl", "pigeon")
>>> print(birds)
('pelican', 'owl', 'chug')
Seem Familiar?
We've actually seen and used tuples in the past! Does anyone remember where we've seen tuples before?
String formatting with the % operator:
"I've % s this % s before!" % ( "seen" , "this" )
Multiple assignment
a , b , c = 1 , 2 , 3
What About Function Parameters?
Aren't function parameters comma separated?
Function parameters (both in definitions and when calling functions) are not tuples, even though they're comma separated
In order to pass a tuple literal to a function, you have to use parentheses to delimit the tuple to prevent ambiguity
>>> print(1, 2)
1 2
>>> print((1, 2))
(1, 2)
Tuple Operations and Built-In Functions
a tuple is a sequence type, so it has some operations that are similar to strings and lists…
but there are some operations that it doesn't support
Tuple Operations and Built-In Functions Continued
Let's try the following:
Supported Operations:
multiplication and addition
indexing and slicing
len
for … in
in / not in
Unsupported Operations:(because it is immutable, these methods will not work) append, extend, remove, etc.
Tuple Operations Examples
Some operations:
a = ( 1 , 2 , 3 )
print ( a + ( 4 , 5 , 6 ))
print ( a [ 0 ])
print ( a [: 2 ])
print ( len ( a ))
print ( 5 in a )
( 1 , 2 , 3 , 4 , 5 , 6 )
1
( 1 , 2 ) # note that slicing a tuple returns a tuple!
3
False
Iteration
Just like iterating over strings or lists.
for value in ( 1 , 2 , 3 ):
print ( value )
Tuple Unpacking / Multiple Assignment
We talked briefly talked about multiple assignment. This is generally done with tuples, and when it's done with tuples, it's called tuple unpacking .
a tuple of variables on the left of an assignment operator
a tuple of values on the right of an operator
both have the same number of elements
each value is assigned to each variable in the order that the elements are in
>>> first_name, last_name = ("Hiro", "Protagonist")
>>> print(first_name)
Hiro
>>> print(last_name)
Protagonist
Tuple Unpacking Examples
What does this code output?
values = ( 1 , 2 , 3 )
a , b , c = values
print ( a )
print ( b )
c , a , b = values
print ( a )
print ( b )
List of Tuples
A tuple within a list is retrieved as a single object, as with every other element in a list, when using our regular for loop_variable in some_list syntax:
characters = [( "Hiro" , "Protagonist" ), ( "Yours" , "Truly" )]
for character in characters :
print ( character )
You get each actual tuple, so this prints out:
( 'Hiro' , 'Protagonist' )
( 'Yours' , 'Truly' )
List of Tuples Continued
Unpacking works in for loops as well! Imagine that each element is retrieved form the outer list. Each element is a tuple which can be unpacked into multiple loop variables.
characters = (( "Hiro" , "Protagonist" ), ( "Yours" , "Truly" ))
for first , last in characters :
print ( "first name is " + first )
print ( "last name is " + last )
List of Tuples Example
pairs_of_numbers = [( 1 , 2 ), ( 2 , 3 )]
for a , b in pairs_of_numbers :
print ( a + b )
Returning Tuples
Tuples and tuple unpacking can provide a method of returning multiple values from a function. What do you think this prints out?
def calculate_3d_point ():
result = ( 2 , 4 , 0 )
return result
x , y , z = calculate_3d_point ()
print ( "the z coordinate is % s" % ( z ))
print ( "the x coordinate is % s" % ( 2 ))
the z coordinate is 0
the x coordinate is 2
Tuples Exercise
What are two ways of programmatically drawing a square in turtle?
What are some ways of representing a series of four x, y coordinates?
there are a couple of ways to draw a square with turtle:
for loop and a combination of either left or right and forward or back
goto
as literals, as separate variables… or as a tuple of tuples!
Tuples Exercise
create a tuple of tuple literals that represent x, y coordinates of corners of a square
assume that the bottom left corner is at (0, 0) and the upper right is (0, 50)
assign that tuple to a variable
use a for loop and tuple unpacking to get each x, y value
within the for loop, use goto with your loop variables to draw the square
Template
import turtle
t = turtle . Turtle ()
wn = turtle . Screen ()
# your code here!
wn . mainloop ()
Tuples Solution
import turtle
t = turtle . Turtle ()
wn = turtle . Screen ()
for x , y in [( 0 , 50 ),( 50 , 50 ),( 50 , 0 ),( 0 , 0 )]:
t . goto ( x , y )
wn . mainloop ()
That's cool and all… but why would an immutable list ever be useful?
When To Use Tuples Continued
some Python constructs use tuples (interpolation, multiple assignment)
tuples are write protected
prevent an object from being changed
example: constants - values that never change… like origin = (0, 0)
tuples are faster than lists for some operations
returning multiple values from a function
semantics
treat related data as a whole
example: points in a 2-dimensional plane