CIS 1051 - Temple Rome Spring 2023¶

Intro to Problem solving and¶

Programming in Python¶

LOGO

LOGO

Tuples¶

Prof. Andrea Gallegati

( tuj81353@temple.edu )

Tuples Are Immutable¶

A tuple is a sequence of values.

These values:

  • can be any type
  • are indexed by integers

Tuples are a lot like lists.

The important difference is that tuples are immutable.

Syntactically, it is a comma-separated list of values:

In [1]:
t = 'a', 'b', 'c', 'd', 'e'

Although not necessary, it's common to enclose them into parentheses:

In [2]:
t = ('a', 'b', 'c', 'd', 'e')

To create a tuple with a single element, include a final comma:

In [3]:
t1 = 'a',
type(t1)
Out[3]:
tuple

A single value within parentheses is not a tuple:

In [4]:
t2 = ('a')
type(t2)
Out[4]:
str

... otherwise, use the built-in function tuple.

Without argument, it creates an empty tuple:

In [5]:
t = tuple()
t
Out[5]:
()

or with a sequence argument (string, list or tuple)

In [6]:
t = tuple('lupins')
t
Out[6]:
('l', 'u', 'p', 'i', 'n', 's')

... avoid using tuple as a variable name.

Most list operators also work on tuples.

The square bracket operator indexes an element:

In [7]:
t = ('a', 'b', 'c', 'd', 'e')
t[0]
Out[7]:
'a'

The slice operator selects a range of elements:

In [8]:
t[1:3]
Out[8]:
('b', 'c')

When trying to modify a tuple element, we get an error:

In [9]:
t[0] = 'A'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-d8f50996a189> in <module>()
----> 1 t[0] = 'A'

TypeError: 'tuple' object does not support item assignment

Tuples are immutable.

We can replace a tuple with another:

In [10]:
t = ('A',) + t[1:]
t
Out[10]:
('A', 'b', 'c', 'd', 'e')
  • making a new tuple
  • making t refer to it

relational operators work with tuples and other sequences.

In [12]:
(0, 1, 2) < (0, 3, 4)
Out[12]:
True
  • Python compares the sequence elements.
  • If equal, it goes on to the next elements.
  • It stops, when two elements differ.
In [13]:
(0, 1, 2000000) < (0, 3, 4)
Out[13]:
True

Subsequent elements are then not considered.

Tuple Assignment¶

It's so useful to swap the values between two variables.

In [17]:
temp = a
a = b
b = temp

we have to use a temporary variable.

This is cumbersome: tuple assignment is more elegant!

In [18]:
a, b = b, a
  • left side is a tuple of variables
  • right side is a tuple of expressions
  • Each value is assigned to its respective variable.
  • All the expressions are evaluated before any of the assignments.

Variables on the left must be the same number of values on the right:

In [19]:
a, b = 1, 2, 3
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-19-f840016b8414> in <module>()
----> 1 a, b = 1, 2, 3

ValueError: too many values to unpack (expected 2)

The right side can be any kind of sequence (string, list or tuple).

In [20]:
addr = 'monty@python.org'
uname, domain = addr.split('@')

this splits an email address into

  • a user name
  • a domain

split returns a list with two elements:

In [21]:
uname
Out[21]:
'monty'
In [23]:
domain
Out[23]:
'python.org'

Tuples as Return Values¶

Strictly speaking, functions can return one value only.

If that value is a tuple, same effect as returning multiple values!

Dividing two integers and computing:

  • the quotient
  • the remainder

it's inefficient to compute

x/y 

and then

x%y

divmod built-in function, takes two arguments and returns a tuple of two values:

  • the quotient
  • the remainder
In [24]:
t = divmod(7, 3)
t
Out[24]:
(2, 1)

we can store the result as a tuple

In [25]:
quot, rem = divmod(7, 3)
quot
Out[25]:
2
In [26]:
rem
Out[26]:
1

or use tuple assignment to store them separately.

In [27]:
def min_max(t):
    return min(t), max(t)

another example, making use of these built-in functions finding:

  • max: largest element of a sequence
  • min: smallest element of a sequence

it then returns both as a tuple of two values.

This chapter presents one more built-in type, the tuple.

Then shows how

  • lists
  • dictionaries
  • tuples

work together.

One note: there is no consensus on how to pronounce “tuple”:

  • Some people say “tuh-ple”, which rhymes with “supple”.
  • But in the context of programming, most people say “too-ple”, which rhymes with “quadruple”.