Tuple in Python
Tuple in Python
Python
A tuple is a sequence of immutable
Python objects.
Tuples are sequences, just like lists.
The differences between tuples and lists
are, the tuples cannot be changed unlike
lists and tuples use parentheses, whereas
lists use square brackets.
Creating Tuple
Creating a tuple is as simple as putting
different comma-separated values.
Ex:
t = (1)
print(t[0])
Ex:
t = (1,)
print(t[0])
Accessing Values in Tuples
To access values in tuple, use the square
brackets for slicing along with the index or
indices to obtain value available at that
index.
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print("tup1[0]: ", tup1[0])
print("tup2[1:5]: ", tup2[1:5])
Output:
tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)
Nested tuples are accessed using nested
indexing.
Ex:
t = ("mouse",[8,4,6],(1,2,3))
print(t[0])
print(t[0][3])
print(t[1][2])
Output:
mouse
s
6
Adding elements to tuple
Ex:
t=()
for i in range(5):
t=t+(i,)
print(t)
Output:
(0, 1, 2, 3, 4)
Updating Tuple
Tuples are immutable which means you
cannot update or change the values of
tuple elements once inserted.
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# Following action is not valid for tuples
# tup1[0] = 100
# So let's create a new tuple as follows
tup3 = tup1 + tup2
print(tup3)
Output:
(12, 34.56, 'abc', 'xyz')
If the element is itself a mutable data type
like list, its nested items can be changed.
Ex:
t = ("mouse",[8,4,6],(1,2,3))
t[1][1]=5
print(t)
Output:
('mouse', [8, 5, 6], (1, 2, 3))
Deleting Tuple Elements
Removing individual tuple elements is not
possible.
To explicitly remove an entire tuple, just
use the del statement.
Ex:
tup = ('physics', 'chemistry', 1997, 2000)
print(tup)
del tup
print("After deleting tup : ")
print(tup)
Basic Tuples Operations
Tuples respond to the + and * operators much
like strings; they mean concatenation and
repetition here too, except that the result is a
new tuple, not a string.
Indexing, Slicing
Because tuples are sequences, indexing
and slicing work the same way for tuples
as they do for strings.
Output:
First tuple length : 3
Second tuple length : 2
max(tuple)
Ex:
tuple1, tuple2 = ('xyz', 'zara', 'abc'), (456,
700, 200)
print("Max value element : ", max(tuple1))
print("Max value element : ", max(tuple2))
Output:
Max value element : zara
Max value element : 700
min(tuple)
Ex:
tuple1, tuple2 = ('xyz', 'zara', 'abc'), (456,
700, 200)
print("Max value element : ", min(tuple1))
print("Max value element : ", min(tuple2))
Output:
Max value element : abc
Max value element : 200
tuple(seq)
Ex:
aList = [123, 'xyz', 'zara', 'abc']
aTuple = tuple(aList)
print("Tuple elements : ", aTuple)
Output:
Tuple elements : (123, 'xyz', 'zara', 'abc')
Methods
count(x)
Ex:
t = (1,2,3,1,2,1,4)
print(t.count(1))
Output:
3
index(x)
Ex:
t = (1,2,3,1,2,1,4)
print(t.index(2))
Output:
1
Tuple Membership Test
We can test if an item exists in a tuple or
not, using the keyword in.
Ex:
t = (1,2,3,1,2,1,4)
print(1 in t)
print(2 not in t)
Output:
True
False
Iterating Through a Tuple
Ex:
for name in ('abc','xyz'):
print("Hello",name)
Output:
Hello abc
Hello xyz
Tuple with string functions
Ex:
s=input()
t=tuple(s.split(“ "))
print(t)
Output:
I am student
(‘I', 'am', ‘student')
l=[1,2,(3,4),"hello"]
l[2]=l[2]+(4,)
print(l)
l[2]=(2,1,2)
print(l)
del l[2]
#l[3]=[1,2]
print(l)
Output:
[1, 2, (3, 4, 4), 'hello']
[1, 2, (2, 1, 2), 'hello']
[1, 2, 'hello']
l=(1,2,(3,4),[1,2],"hello")
l=l+(4,)
print(l)
l[3].append(4)
print(l)
Output:
(1, 2, (3, 4), [1, 2], 'hello', 4)
(1, 2, (3, 4), [1, 2, 4], 'hello', 4)
type()
Output:
<class 'tuple'>
my_tuple = ("hello")
print(type(my_tuple)) # <class 'str’>
# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>
Check if item exists
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits
tuple")
Output:
Yes, 'apple' is in the fruits tuple
Change tuple values
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Output:
("apple", "kiwi", "cherry")
print(green)
print(yellow)
print(red)
Output:
apple
banana
cherry
Using Asterisk *
fruits =
("apple", "banana", "cherry", "strawberry", "rasp
berry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
Output:
apple
banana
['cherry', 'strawberry', 'raspberry']
fruits =
("apple", "mango", "papaya", "pineapple", "ch
erry")
print(green)
print(tropic)
print(red)
Output:
apple
['mango', 'papaya', 'pineapple’]
cherry
Problem:
You are required to write a program to sort the
(name, age, height) tuples by ascending order
where name is string, age and height are numbers.
1: Sort based on name;
2: Then sort based on age;
3: Then sort by score.
The priority is that name > age > score. If the
following tuples are given as input to the program:
Tom,19,80
John,20,90
Jony,17,91
Jony,17,93
Then, the output of the program should be:
[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17',
'93'), ('Tom', '19', '80')]
from operator import itemgetter, attrgetter
l = []
while True:
s = raw_input()
if not s:
break
l.append(tuple(s.split(",")))
print sorted(l, key=itemgetter(0,1,2))