0% found this document useful (0 votes)
6 views31 pages

Understanding Python 3 Tuples

tuples
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views31 pages

Understanding Python 3 Tuples

tuples
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

TUPLES

TUPLES

• A tuple is a sequence of items, similar to


lists. The values stored in the tuple can be
of any type and they are indexed using
integers.

• Unlike lists, tuples are immutable. That is,


values within tuples cannot be
modified/reassigned.
Tuples are like lists
• Tuples are another kind • >>> x = ('Glenn',
of sequence that 'Sally', 'Joseph')
function much like a list • >>> print x[2]Joseph
- they have elements • >>> y = ( 1, 9, 2 )
which are indexed
>>> foratiter in y: • >>> print y
starting 0
... print iter • (1, 9, 2)
... • >>> print max(y)
1
• 9
9
2
>>>
TUPLES
A tuple can be created in Python as a comma
separated list of items – may or may not be
enclosed within parentheses.
TUPLES
If we would like to create a tuple with single
value, then just a parenthesis will not suffice. For
example,

Thus, to have a tuple with single item, we must


include a comma after the item. That is,
TUPLES

An empty tuple can be created either


using a pair of parenthesis or using a
function tuple() as below –
TUPLES
TUPLES

Note that, in the above example, both t and t1 objects are


referring to same memory location. That is, t1 is a reference to t.
TUPLES

Elements in the tuple can be extracted using square-


brackets with the help of indices.
TUPLES
t=('Mango', 'Banana', 'Apple’)
>>> t[0]='Kiwi’
TypeError: 'tuple' object does not support item
assignment

We wanted to replace ‘Mango’ by ‘Kiwi’, which did not


work using assignment.
But, a tuple can be replaced with another tuple involving
required modifications:
>>> t=('Kiwi',)+t[1:]
>>> print(t)
('Kiwi', 'Banana', 'Apple’)
Things not to do with
tuples
• >>> x = (3, 2, 1)
• >>> [Link]()
• Traceback:AttributeError: 'tuple' object has no
attribute 'sort’
• >>> [Link](5)
• Traceback:AttributeError: 'tuple' object has no
attribute 'append’
• >>> [Link]()
• Traceback:AttributeError: 'tuple' object has no
attribute 'reverse’
• >>>
Tuples are more efficient

• Since Python does not have to build


tuple structures to be modifiable, they
are simpler and more efficient in terms
of memory use and performance than
lists
• So in our program when we are making
"temporary variables" we prefer tuples
over lists.
Comparing Tuples

Tuples can be compared using operators like >, <, >=,


== etc. The comparison happens lexicographically.

The meaning of < and > in tuples is not exactly less than and greater than, instead,
it means comes before and comes after. Hence in such cases, we will get results
different from checking equality (==).
The comparison operators work with tuples and
other sequences If the first item is equal, Python
goes on to the next element, and so on, until it
finds elements that differ.

• >>> (0, 1, 2) < (5, 1, 2)


• True
• >>> (0, 1, 2000000) < (0, 3, 4)
• True
• >>> ( 'Jones', 'Sally' ) < ('Jones', 'Sam')
• True
• >>> ( 'Jones', 'Sally') > ('Adams', 'Sam')
• True
Comparing Tuples
The sort() function internally works on similar pattern – it sorts
primarily by first element, in case of tie, it sorts on second
element and so on. This pattern is known as DSU:

• Decorate a sequence by building a list of tuples with


one or more sort keys preceding the elements from the
sequence,

• Sort the list of tuples using the Python built-in sort(),


and

• Undecorate by extracting the sorted elements of the


sequence.
Comparing Tuples
Tuple Assignment
Tuple has a unique feature of having it at LHS of
assignment operator. This allows us to assign
values to multiple variables at a time.

When we have list of items, they can be


extracted and stored into multiple variables as
below:
Tuple Assignment
Tuple Assignment
The best known example of assignment of tuples
is swapping two values as below:
Tuple Assignment
While doing assignment of multiple variables, the RHS
can be any type of sequence like list, string or tuple.

Following example extracts user name and domain


from an email ID.
>>> email=‘global@[Link]'
>>> usrName, domain = [Link]('@')
>>> print(usrName)
global
>>> print(domain)
[Link]
Dictionaries and Tuples
Dictionaries have a method called items() that
returns a list of tuples.

where each tuple is a key-value pair as


shown below:
Dictionaries and Tuples
As dictionary may not display the contents in an order, we
can use sort() on lists and then print in required order as
below:
Multiple Assignment with Dictionaries

We can combine the method items(), tuple assignment


and a for-loop to get a pattern for traversing dictionary:
Multiple Assignment with Dictionaries
Using Tuples as Keys in
Dictionaries
As tuples and dictionaries are hashable, when we want a
dictionary containing composite keys, we will use tuples.

For Example, we may need to create a telephone


directory where name of a person is Firstname-last name
pair and value is the telephone number. Our job is to
assign telephone numbers to these keys.
Using Tuples as Keys in
Dictionaries
The most common
words
Summary on Sequences
• Till now, we have discussed different types of
sequences viz. strings, lists and tuples.

• In many situations these sequences can be used


interchangeably.

• Still, due their difference in behavior and ability,


we may need to understand pros and cons of each
of them and then to decide which one to use in a
program.
Summary on Sequences
• Strings are more limited compared to other
sequences like lists and Tuples.

• Because, the elements in strings must be


characters only. Moreover, strings are immutable.

• Hence, if we need to modify the characters in a


sequence, it is better to go for a list of characters
than a string.
Summary on Sequences
As lists are mutable, they are most common compared to
tuples. But, in some situations as given below, tuples are
preferable.

• When we have a return statement from a function, it is


better to use tuples rather than lists.

• When a dictionary key must be a sequence of elements,


then we must use immutable type like strings and tuples

• When a sequence of elements is being passed to a


function as arguments, usage of tuples reduces
unexpected behavior due to aliasing.
Summary on Sequences

• As tuples are immutable, the methods like


sort() and reverse() cannot be applied on
them.

• But, Python provides built-in functions


sorted() and reversed() which will take a
sequence as an argument and return a new
sequence with modified results.

You might also like