0% found this document useful (0 votes)
38 views29 pages

Tuples

Uploaded by

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

Tuples

Uploaded by

KETKI SONAWANE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Tuples

Introduction
 A tuple is essentially an immutable list.
 Below is a tuple with three elements:
T = (1, 2, 3)
 Tuples are enclosed in parentheses, but the parentheses
are optional.
 Indexing and slicing work the same as with lists.
 As with lists, you can get the length of the tuple by using
the len function.
 Like lists, tuples have count and index methods.
 However, since a tuple is immutable, it does not have any
of the other methods that lists have, like sort or reverse.
Continued…..
 We have seen tuples in a few places already.
 The dictionary method items return a list of tuples.
 Also, when we use the following shortcut for exchanging
the value of two or more variables, we are actually using
tuples:
a,b = b,a
Applications
 Tuples are used in some situations where you want an
immutable type of list.
 Tuples can serve as keys in dictionaries.
 Here is an example of assigning grades to the teams of
students:
grades = {('John', 'Ann'): ‘A’, ('Mike', 'Tazz'): ‘B’}
 The flexibility of lists comes with a corresponding cost in
speed. Tuples are generally faster than lists.
Creating a tuple
 A tuple is created by placing all the items (elements) inside the
parentheses (), separated by comma.
 It is a good practice to write parentheses even though they are
optional.
 A tuple can have any number of items and they may be of
different data types (integer, float, list, string etc.).

1.Empty tuple
T = ()
print(T)

 Output:
()
Continued…..
2.Tuple having integers
T = (1, 2, 3)
print(T)

 Output:
(1, 2, 3)

3.Tuple with mixed datatypes


T = (1, "Hello", 3.4)
print(T)

 Output:
(1, 'Hello', 3.4)
Continued…..
4. Nested tuple
T = ("mouse", [8, 4, 6], (1, 2, 3))
print(T)
5. Tuple can be created without parentheses
T = 3, 4.6, “Hello”
print(T)
6. Tuple unpacking is also possible
a, b, c = T
print(a)
print(b)
print(c)
Creating a tuple with one element
 Creating a tuple with one element is a bit tricky.
 Having one element within parentheses is not enough.
 We will need a comma following the element to indicate
that it is a tuple.
T = (5, )
print(T)

 Output:
(5, )
Accessing Elements in a Tuple
 There are various ways in which we can access the
elements of a tuple.
Indexing
 We can use the index operator [ ] to access an item in a
tuple where the index starts from 0.
 So, a tuple having 6 elements will have index from 0 to 5.
 Trying to access an element other than that (6, 7,...) will
raise an Index Error.
 The index must be an integer, so we cannot use float or
other types.
 This will result into Type Error.
Example
 Example 1:
T = ('H', 'e', 'l', 'l', 'o')
print(T[0])
print(T[4])
print(T[-1])

 Output:
H
o
o
Continued…..
 Nested tuples are accessed using nested indexing, as
shown in the example below.
 Example 2:
T2 = ("mouse", [8, 4, 6], (1, 2, 3))
print(T2[0][3])
print(T2[1][1])

 Output:
s
4
Slicing
 We can access a range of items in a tuple by using the
slicing operator - colon ":".
 If we want to access a range, we need the index that will
slice the portion from the tuple.
Example
T = ('h', 'e', 'l', 'l', 'o')
print(T[1:3])
print(T[:-5])
print(T[4:])
print(T[:])

 Output:
('e', 'l')
('h',)
('o',)
('h', 'e', 'l', 'l', 'o')
Changing a Tuple
 Unlike lists, tuples are immutable.
 This means that elements of a tuple cannot be changed once it
has been assigned. But, if the element is itself a mutable
datatype like list, its nested items can be changed.
 We can also assign a tuple to different values (reassignment).
 Example:
T = (4, 2, 3, [6, 5])
T[3][0] = 9
print(T)

 Output:
(4, 2, 3, [9, 5])
Continued…..
 We can use + operator to combine two tuples.
 This is also called concatenation.
 We can also repeat the elements in a tuple for a given
number of times using the * operator.
 Both + and * operations result into a new tuple.
 Example:
print((1, 2, 3) + (4, 5, 6))
print(("Repeat",) * 3)

 Output:
(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')
Add or Removing Items
 Once a tuple is created, you cannot add items to it or
remove items from it.
 Tuples are unchangeable.

T = ("apple", "banana", "cherry")


T[3] = "orange" # This will raise an error
print(T)
Deleting a Tuple
 As discussed above, we cannot change the elements in a
tuple. That also means we cannot delete or remove items
from a tuple.
 But deleting a tuple entirely is possible using the
keyword del.
 Example:
T = ('h', 'e', 'l', 'l', 'o')
del T
print(T)
Tuple built_in functions
Method Description
len returns the number of items in the list
min returns the minimum of the items in the list
max returns the maximum of the items in the list
Take elements in the tuple and return a new sorted list (does not sort the
sorted()
tuple itself).
sum() Retrun the sum of all elements in the tuple.
tuple() Convert an iterable (list, string, set, dictionary) to a tuple.
Return True if all elements of the tuple are true (False if the tuple is
all()
empty).
Return True if any element of the tuple is true. If the tuple is empty,
any()
return False.
Return an enumerate object. It contains the index and value of all the
enumerate()
items of tuple as pairs.
Python Tuple Methods
 Methods that add items or remove items are not available
with tuple.
 Only the following two methods are available.

Method Description
Return the number of items that
count(x)
is equal to x
Return index of first item that is
index(x)
equal to x
Example
T = ('h', 'e', 'l', 'l', 'o')
print(T.count(‘l’))
print(T.index(‘e’))

 Output:
2
1
Converting list to a Tuple
L = [0, 1, 2]
print(tuple(L))

 Output:
(0, 1, 2)
Converting string to a Tuple
S='Python'
print(tuple(S))

 Output:
('p', 'y', 't', 'h', 'o', 'n')
Converting dictionary to a Tuple
D = {'Name' : 'xyz', 'Rollno' : 2, 'Marks' : 34.5}
print(tuple(D))
print(tuple(D.values()))
print(tuple(D.items()))

 Output:
('Name', 'Rollno', 'Marks')
('xyz', 2, 34.5)
(('Name', 'xyz'), ('Rollno', 2), ('Marks', 34.5))
Find output
t=(1,2,4,3)
t[1:-1]
Find output
t = (1, 2, 4, 3, 8, 9)
[t[i] for i in range(0, len(t), 2)]
Find output
t = (1, 2, 3, 4)
t.append( (5, 6, 7) )
print(len(t))
Find output
a = (‘Hello',)
b=2
for i in range(int(b)):
a = (a,)
print(a)
Find output
a=(1,2)
b=(3,4)
c=a+b
print(c)

You might also like