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

Python 11 Tuple

The document explains tuples in Python, highlighting their characteristics such as immutability, creation, and methods for accessing and manipulating tuple elements. It includes examples of creating tuples, accessing elements via indexing and slicing, and using membership operators. Additionally, it covers tuple functions like len(), index(), max(), min(), sum(), count(), sorted(), and reversed().

Uploaded by

namitchopra2009
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)
6 views12 pages

Python 11 Tuple

The document explains tuples in Python, highlighting their characteristics such as immutability, creation, and methods for accessing and manipulating tuple elements. It includes examples of creating tuples, accessing elements via indexing and slicing, and using membership operators. Additionally, it covers tuple functions like len(), index(), max(), min(), sum(), count(), sorted(), and reversed().

Uploaded by

namitchopra2009
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/ 12

It is an ordered collection of objects.

Tuple is immutable or unchangeable, ordered sequence of


elements. But unlike strings, which can only contain characters, tuples can contain elements of any
type. Unlike lists, however, tuples are enclosed within parentheses [ ( ) ]. Tuples are good to use than
lists because:
➢ Tuples are faster than lists. If you are defining a constant set of values and all you will do with it is
iterate through it, use a tuple instead of a list.
➢ Tuples make your code safer if you “write-protect” data that do not need to be changed.

Creating Tuple
To create a tuple, you separate the elements with a comma and enclose them with a parentheses “( ). The
syntax is:
tuple-variable = (val1, val2, val3, ....., valn)
For example:
>>> Num = (67, 82, 98, 92, 78, 87, 82)
>>> print (Num) # prints all elements
(67, 82, 98, 92, 78, 87, 82)
>>> WeekDays = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
>>> print (WeekDays)
('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday') Reeta Sahoo & Gagan Sahoo
>>> states = () # an empty tuple
Accessing Tuple Elements
Accessing the elements in a tuple is just like a list. We can access individual tuple elements
using indexing and a range of elements using slicing. A tuple index starts from 0.
Python indexes the tuple element from left to right and from right end to left. From left to
right, the first element of a tuple has the index 0 and from right end to left, the extreme right
index element of a tuple is –1. Individual elements in a tuple can be accessed by specifying
the tuple name followed
Let us two different lists with different values

Index from left 0 1 2 3 4 5 6

List with numbers 67 82 98 92 78 87 82

List with strings Sunday Monday Tuesday Wednesday Thursday Friday Saturday

Index from right end –7 –6 –5 –4 –3 –2 –1

For example:
>>> print (Num[3]) # prints 4th element: 92
>>> print (Num[-1]) # prints last element: 82
>>> print (WeekDays[4]) # prints 5th element: Tursday
>>> print (WeekDays[-1]) # prints last element: Saturday
Reeta Sahoo & Gagan Sahoo
Slicing Tuple Elements
Selecting a slice is similar to selecting an element(s) of a list. Subsets of lists can be taken using the slice
operator with two indices in square brackets separated by a colon ( [m:n] ).
The operator [m:n] returns the part of the list from the mth position and up to but not including
position n, i.e., n – 1.
[2:6]
[-5:-1]
Index from left 0 1 2 3 4 5 6

List with numbers 67 82 98 92 78 87 82

List with strings Sunday Monday Tuesday Wednesday Thursday Friday Saturday

Index from right end –7 –6 –5 –4 –3 –2 –1

For example:
>>> Num = (67, 82, 98, 92, 78, 87, 82)
>>> print (Num[2:6]) # prints: (98, 92, 78, 87)
>>> print (Num[:4]) # prints every thing upto but not including 4, i.e., (67, 82, 98, 92)
>>> print (Num[-5:-1]) # prints: (98, 92, 78, 87)
>>> print (Num[-5:]) # prints last five elements: (98, 92, 78, 87, 82)
>>> print (Num[-4:-2]) # prints third and fourth element from the last: (92, 78)
Reeta Sahoo & Gagan Sahoo
Tuples are Immutable
Tuples are immutable which means that after initializing a tuple, it is impossible to update individual
items in a tuple.
For example:

>>> x = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)


>>> x[1] = 100
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
x[1] = 100
TypeError: 'tuple' object does not support item assignment

Reeta Sahoo & Gagan Sahoo


Concatenating & Replicating List
You can concatenate tuples the same way you concatenate strings. You simply join them together
with +, the concatenation operator. For example,

Item1 Item2
Pen Pencil Rubber Scale + Eraser Paper Clip Refill

Item1 + Item2
= Pen Pencil Rubber Scale Eraser Paper Clip Refill

For example:
>>> Item1 = ('Pen', 'Pencil', 'Rubber', 'Scale') # First tuple
>>> Item2 = ('Eraser', 'Clips and Pins', 'Refill') # Second tuple
>>> Item1 = Item1 + Item2 # Adding two tuples
>>> print (Item1)
('Pen', 'Pencil', 'Rubber', 'Scale', 'Eraser', 'Clips and Pins', 'Refill')

Note : In statement, Item1 = Item1 + Item2


Item1 on left side is a new variable which is the sum of previous variables Item1 and
Item2.
Reeta Sahoo & Gagan Sahoo
Replicating Tuple

Tuple can be replicated or repeated or repeatedly concatenated with the asterisk operator "*".

aTuple aTuple *3
1 2 3 *3 = 1 2 3 1 2 3 1 2 3

For example:

>>> aTuple = (1, 2, 3)


>>> aTuple*3 # a tuple can only multiplied by a positive integer
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> aTuple*-1
?

>>> aTuple*aTuple
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
aTuple*aTuple
TypeError: can't multiply sequence by non-int of type 'tuple'

Reeta Sahoo & Gagan Sahoo


Programming examples (Iterating) [Traversing]:

Write a program to print the following tuple elements using for loop:
WeekDays = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')

WeekDays = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')


print('Weekdays are: ', end='')
for wd in WeekDays:
print(wd, end= ' ')
Or
print('Weekdays are: ', end='')
for wd in ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'):
print(wd, end= ' ')
Or
WeekDays = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
print('Weekdays are: ', end='')
Length = len(WeekDays)
for i in range(0, Length):
print(WeekDays[x], end= ' ')

Output:
Weekdays are: Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Using Membership Operators with Tuple
The implementation of membership operators with tuple is exactly same as other sequence like lists
and string. There are two types of membership operators.

Operator Description
in This operator tests if an element is present in tuple or not. If an element exists in
the tuple, it returns True, otherwise False. For example,
>>> aTuple = (1, 15, 10, 5, -99, 100)
>>> print(10 in aTuple) # returns: True
>>> print(-50 in aTuple) # returns: False
>>> Months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun')
>>> 'Dec' in Months # returns: False
not in The not in operator evaluates True if it does not find a variable in the specified
sequence, otherwise False. For example,
>>> aTuple = (1, 15, 10, 5, -99, 100)
>>> print(10 not in aTuple) # returns: False
>>> print(-100 not in aTuple) # returns: True
>>> Months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun')
>>> 'Dec' not in Months # returns: True

Reeta Sahoo & Gagan Sahoo


Programming example

A tuple called Festival is given with following elements:


Festival = ('Lumbini', 'Mopin', 'Bihu', 'Chhath', 'Onam', 'Lohri', 'Pongal', 'Garba‘)
Write a program to enter a festival name and search whether the name present in the tuple or
not using membership operator. Print appropriate message.

Festival = ('Lumbini', 'Mopin', 'Bihu', 'Chhath', 'Onam', 'Lohri', 'Pongal', 'Garba‘)


nfest = input('Enter festival name: ').capitalize() #input value capitalize
if nfest in Festival: # membership operator ‘in’ is used
print("Yes,", nfest, ‘is in the tuple.')
else:
print("There is no such name in the tuple.")

Output:
Enter festival name: onam
Yes, Onam is in the tuple.

Enter festival name: Thrissur


There is no such name in the tuple.

Reeta Sahoo & Gagan Sahoo


Programming example
A tuple called Festival is given with following elements:
Festival = ('Lumbini', 'Mopin', 'Bihu', 'Chhath', 'Onam', 'Lohri', 'Pongal', 'Garba‘)
Write a program to enter a festival name and search whether the name present in the tuple or
not without using membership operator. Print appropriate message.

Festival = ('Lumbini', 'Mopin', 'Bihu', 'Chhath', 'Onam', 'Lohri', 'Pongal', 'Garba')


nfest = input('Enter festival name: ').capitalize() #input value capitalize
Length = len(Festival)
Flag = False
for x in range(Length):
if Festival[x] == nfest :
Flag = True
break; # if the festival name exists, then terminate the loop
if Flag == True:
print("Yes,", nfest, ' is in the tuple.')
else:
print("There is no such name in the tuple.")

Output:
Enter festival name: onam
Yes, Onam is in the tuple.

Enter festival name: Thrissur Reeta Sahoo & Gagan Sahoo


There is no such name in the tuple.
Tuple Functions
A lot of functions that work on lists work on tuples too. A function applies on a construct and returns a
result. It does not modify the construct.

Description
Function Name = ['Anmol', 'Kiran', 'Vimal', 'Sidharth', 'Riya']
Num = [23, 54, 34, 44, 35, 66, 27, 88, 69, 54]
len() This method returns the length of the tuple.
WeekDays = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
print (len(WeekDays)) # prints: 7
Index() This function finds the first occurrence of a value in the tuple and returns the index value.
WeekDays = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
print ("The index position of 'Tuesday' is:", WeekDays.index('Tuesday'))
The index position of 'Tuesday' is: 2
max() This function returns the maximum/largest value from the tuple.
TotalMarks = (450, 460, 460, 486, 466, 482, 489,476)
print ("Maximum mark is:", max(TotalMarks)) # prints: Maximum mark is: 489
mix() This function returns the minimum/smallest value from the tuple.
TotalMarks = (450, 460, 460, 486, 466, 482, 489,476)
print ("Minimum mark is:", min(TotalMarks)) # prints: Minimum mark is: 450
sum() This function returns the sum of a sequence or tuple. The sequence elements must be numeric
type.
Subject5 = (76, 78, 87, 89, 92)
print ('Total mark is:', sum(Subject5)) # prints: Total mark is: 422
List function continues….

Function Description
count() This method counts how many times of an object occurs in a tuple.
ntuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = ntuple.count(5)
print(x) # returns: 2
sorted() This method is used to return a sorted list of a tuple. Since tuples are arrays that you cannot
modify, they do not have an in-place sort function that can be called directly on them.
Name = ('Anmol', 'Kiran', 'Vimal', 'Amit', 'Sidharth', 'Riya', 'Sneha')
sorted(Name) # Or NewNames = sorted(Name)
# returns: ['Amit', 'Anmol', 'Kiran', 'Riya', 'Sidharth', 'Sneha', 'Vimal']
TotalMarks = (450, 460, 460, 486, 466, 482, 489,476)
print ('Sorted marks:', sorted(TotalMarks))
# prints: Sorted marks: [450, 460, 460, 466, 476, 482, 486, 489]
reversed() The method is used to reverse a tuple and returns an iterator. The
method gets a return value and they will leave the original tuple
unmodified.
Name = ['Anmol', 'Kiran', 'Vimal', 'Amit', 'Sidharth', 'Riya', 'Sneha']
Nm = reversed(Name) # Nm is an iterator
print (Nm) # prints: <reversed object at 0x024DCD50>
for i in Nm:
print (i, end=" ")
# prints: Sneha Riya Sidharth Amit Vimal Kiran Anmol

Reeta Sahoo & Gagan Sahoo

You might also like