0% found this document useful (0 votes)
89 views

Tuples Are Immutable: T 'A', 'B', 'C', 'D', 'E'

Tuples are immutable sequences of values that can contain any type. They are similar to lists but cannot be modified after creation. Tuples are created using commas to separate values and can optionally use parentheses. Common list operations like indexing and slicing also work on tuples but item assignment is not allowed since tuples are immutable. Tuples are often used to return multiple values from functions and as keys in dictionaries.

Uploaded by

Rameshwar Kanade
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)
89 views

Tuples Are Immutable: T 'A', 'B', 'C', 'D', 'E'

Tuples are immutable sequences of values that can contain any type. They are similar to lists but cannot be modified after creation. Tuples are created using commas to separate values and can optionally use parentheses. Common list operations like indexing and slicing also work on tuples but item assignment is not allowed since tuples are immutable. Tuples are often used to return multiple values from functions and as keys in dictionaries.

Uploaded by

Rameshwar Kanade
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
You are on page 1/ 15

Tuples are immutable

 A tuple is a sequence of values.


 The values can be any type, and they are indexed by integers,
so in that respect tuples are a lot like lists.
 The important difference is that tuples are immutable.
 Syntactically, a tuple is a comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'
 Although it is not necessary, it is common to enclose tuples in
parentheses:
>>> t = ('a', 'b', 'c', 'd', 'e')
 To create a tuple with a single element, you have to include a
final comma:
>>> t1 = 'a',
>>> type(t1)
<class 'tuple'>

Python Programming 1
Tuples are immutable Contd.
 A value in parentheses is not a tuple:
>>> t2 = ('a')
>>> type(t2)
<class 'str'>
 Another way to create a tuple is the built-in function tuple.
With no argument, it creates an empty tuple:
>>> t = tuple()
>>> t
()
 If the argument is a sequence (string, list or tuple), the result
is a tuple with the elements of the sequence:
>>> t = tuple('lupins')
>>> t
('l', 'u', 'p', 'i', 'n', 's')

Python Programming 2
Tuples are immutable Contd.
 Most list operators also work on tuples.
 The bracket operator indexes an element:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> t[0]
'a'
 The slice operator selects a range of elements.
>>> t[1:3]
('b', 'c')
 But its not allowed to modify the elements of the tuple (tuples
are immutable). Doing so will fetch an error:
>>> t[0] = 'A'
TypeError: object doesn't support item assignment

Python Programming 3
Tuples are immutable Contd.
 Because tuples are immutable, you can’t modify the elements.
But you can replace one tuple with another:
>>> t = ('A',) + t[1:]
>>> t
('A', 'b', 'c', 'd', 'e')

# This statement makes a new tuple and then makes t refer to it.
 The relational operators work with tuples and other sequences
 Python starts by comparing the first element from each sequence.
If they are equal, it goes on to the next elements,and so on, until it
finds elements that differ. Subsequent elements are not considered
(even if they are really big).
>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
Python Programming 4
Tuple assignment
 It is often useful to swap the values of two variables.
 With conventional assignments, you have to use a temporary
variable. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
 This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a

#The left side is a tuple of variables; the right side is a tuple of


expressions. Each value is assigned to its respective variable.

Python Programming 5
Tuple assignment contd.
 The number of variables on the left and the number of values
on the right have to be the same:
>>> a, b = 1, 2, 3

Output: ValueError: too many values to unpack


 The right side can be any kind of sequence (string, list or
tuple).
 For example, to split an email address into a user name and a
domain, you could write:
>>> addr = 'monty@python.org'
>>> uname, domain = addr.split('@')

Output: >>> uname 'monty'


>>> domain 'python.org'
# The return value from split is a list with two elements; the first
element is assigned to uname, the second to domain.

Python Programming 6
Tuples as return values
 Strictly speaking, a function can only return one value, but if
the value is a tuple, the effect is the same as returning multiple
values.
 The built-in function divmod takes two arguments and returns a
tuple of two values, the quotient and remainder. The result can be
stored as a tuple:
>>> t = divmod(7, 3)
>>> t

Output: (2, 1)
 Or store the elements separately by using tuple assignment
>>> quot, rem = divmod(7, 3)

Output: >>> quot 2


>>> rem 1

Python Programming 7
Tuples as return values contd.
 max and min are built-in functions that find the largest and
smallest elements of a sequence. An example min_max function
has been designed to computes both and returns a tuple of two
values
>>>def min_max(t):
return min(t), max(t)

>>>t = (3, 6, 1, 8, 9)
>>>Minimum, maximum = min_max(t)
>>> Minimum, maximum

Output:
(1, 9)

Python Programming 8
Variable-length argument
tuples
 Functions can take a variable number of arguments. A
parameter name that begins with * gathers arguments into a
tuple.
 For example, printall takes any number of arguments and prints
them:
def printall(*args):
print(args)
>>> printall(1, 2.0, '3')

Output: (1, 2.0, '3')


 If you have a sequence of values and you want to pass it to a
function as multiple arguments, you can use the * operator.
 For example, divmod takes exactly two arguments; it doesn’t work
with a tuple:
>>> t = (7, 3)
>>> divmod(t)

Python Programming 9
Variable-length argument
tuples contd.
Output:
TypeError: divmod expected 2 arguments, got 1

#But if you scatter (The complement of gather is scatter) the tuple, it


works:

>>> divmod(*t)
(2, 1)
 Many of the built-in functions use variable-length argument
tuples.
 For example, max and min can take any number of arguments:
>>> max(1, 2, 3)
3
 But sum does not.
>>> sum(1, 2, 3)
TypeError: sum expected at most 2 arguments, got 3

Python Programming 10
Lists and tuples
 In order to return a list of tuples, a built-in function called ‘zip’
is used.
 The zip takes two or more sequences and returns a list of tuples
where each tuple contains one element from each sequence.
 Here is an example to zip a string and a list:
>>> s = 'abc'
t = [0, 1, 2]
zip(s, t)
#the result is a zip object created. To iterate through the zip object a
for loop may be used
>>> for pair in zip(s, t):
print(pair)

Output: ('a', 0)
('b', 1)
('c', 2)

Python Programming 11
Lists and tuples contd.
 If you want to use list operators and methods, you can use a
zip object to make a list:
 For example, to create a list of tuple from s and t declared in the
previous example, following code may be used.
>>> list(zip(s, t))

Output: [('a', 0), ('b', 1), ('c', 2)]


 If the sequences are not the same length, the result has the length
of the shorter one.
>>> list(zip('Anne', 'Elk'))

Output: [('A', 'E'), ('n', 'l'), ('n', 'k')]


 A for loop can be used to traverse a list of tuples:
t = [('a', 0), ('b', 1), ('c', 2)]
for letter, number in t:
print(number, letter)

Python Programming 12
Lists and tuples contd.
Output: 0 a
1b
2c

 Useful functionalities can be obtained by traversing two (or more)


sequences at the same time. For example, has_match takes two
sequences, t1 and t2, and returns True if there is an index i such
that t1[i] == t2[i]:
def has_match(t1, t2):
for x, y in zip(t1, t2):
if x == y:
return True
return False

Python Programming 13
Dictionaries and tuples
 Dictionaries have a method called items that returns a
sequence of tuples, where each tuple is a key-value pair
 The result is a dict_items object, which is an iterator that iterates
the key-value pairs. A for loop can be used to iterate over it
>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>> t

Output: dict_items([('c', 2), ('a', 0), ('b', 1)])


# Use for loop to iterate the key-value pairs
>>> for key, value in d.items():
print(key, value)

Output: c 2
a0
b1

Python Programming 14
Dictionaries and tuples Contd.
 Going in the other direction, a list of tuples can be used to
initialize a new dictionary:
>>> t = [('a', 0), ('c', 2), ('b', 1)]
>>> d = dict(t)
>>> d

Output: {'a': 0, 'c': 2, 'b': 1}


 Combining dict with zip yields a concise way to create a dictionary:
>>> d = dict(zip('abc', range(3)))
>>> d

Output: {'a': 0, 'c': 2, 'b': 1}


 The dictionary method update also takes a list of tuples and adds
them, as key-value pairs, to an existing dictionary.
 It is common to use tuples as keys in dictionaries (primarily
because you can’t use lists).

Python Programming 15

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy