36.Tuples in python-functions,Operations, Example Programs
Tuples are used for grouping data.A tuple is an immutable list, i.e. a tuple cannot be changed in any way once it has been created. A tuple is defined analogously to lists, except that the set of elements is enclosed in parentheses instead of square brackets. The rules for indices are the same as for lists. Once a tuple has been created, you can't add elements to a tuple or remove elements from a tuple.
- Tuples are faster than lists.
- If you know that some data doesn't have to be changed, you should use tuples instead of lists, because this protects your data against accidental changes.
- Tuples can be used as keys in dictionaries, while lists can't.
Furthermore we can see that we raise an error, if we try to assign a new value to an element of a tuple:
Tuple creation
It is defined within parentheses () where items are separated by commas.
>>> t = ("tuples", "are", "immutable")
To create a tuple with a single element, we have to include the final comma:
>>> t1 = ('a',)
>>> type(t1)
<type ’tuple’>
Without the comma, Python treats ('a') as a string in parentheses:
>>> t2 = ('a')
>>> type(t2)
<type ’str’>
This will create an empty tuple
>>> t=()
>>> type(t)
<type 'tuple'>
>>> t=tuple()
>>> type(t)
<type 'tuple'>
>>> t = ("tuples", "are", "immutable")
To create a tuple with a single element, we have to include the final comma:
>>> t1 = ('a',)
>>> type(t1)
<type ’tuple’>
Without the comma, Python treats ('a') as a string in parentheses:
>>> t2 = ('a')
>>> type(t2)
<type ’str’>
This will create an empty tuple
>>> t=()
>>> type(t)
<type 'tuple'>
>>> t=tuple()
>>> type(t)
<type 'tuple'>
A tuple can also be created without using parentheses. This is known as tuple packing.
>>>t = 3, 4.6, "dog"
>>>print(t)
(3, 4.6, 'dog')
Accessing Elements
t = ("tuples", "are", "immutable")
>>> t[0]
'tuples'
'tuples'
We can use the slicing operator [] to extract items but we cannot change its value.
>>> t[0]="assignments to elements are not possible"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t[0]="assignments to elements are not possible"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>t[-1]
'immutable'
>>>t[0:2]
('tuples','are')
This will add a new element to the Tuple
>>>t=(10,20,30)
>>>t=t+(40,)
>>>t
(10,20,30,40)
This will add a new element to the Tuple
>>>t=(10,20,30)
>>>t=t+(40,)
>>>t
(10,20,30,40)
Tuple operations are similar to list
Example
>>>a=(10,20,30)
>>>b=(40,50)
>>>a+b
(10,20,30,40,50)
>>>b*2
(40,50,40,50)
>>>10 in a
True
>>>100 not in a
True
>>>c=a+(30,)
>>>c
(10,20,30,30)
Tuple Functions
>>>a=(10,20,30,30)
>>>min(a)
10
>>>max(a)
30
>>>sum(a)
90
>>>len(a)
4
>>>a.index(20)
1
>>>a.count(30)
2
cmp( ) # Not available in Python 3
>>>min(a)
10
>>>max(a)
30
>>>sum(a)
90
>>>len(a)
4
>>>a.index(20)
1
>>>a.count(30)
2
cmp( ) # Not available in Python 3
This is used to check whether the given tuples are same or not. If both are same, it will return ‘zero’, otherwise return 1 or -1. If the first tuple is big, then it will return 1,otherwise return -1.
>>>a=(10,20)
>>>b=(10,20)
>>>cmp(a,b)
0
>>>a=(100,200)
>>>b=(10,20)
>>>cmp(a,b)
1
>>>cmp(b,a)
-1
>>>b=(10,20)
>>>cmp(a,b)
0
>>>a=(100,200)
>>>b=(10,20)
>>>cmp(a,b)
1
>>>cmp(b,a)
-1
since the tuples are immutable you cannot sort the tuple.However you can use the sequence function sorted() to create a new sorted list from the tuple.
>>>a=(3,2,4)
>>>sorted(a)
>>>sorted(a)
[2,3,4]
del() function will delete a tuple
>>>del(a)
Tuple packing and unpacking
In tuple unpacking, the values in a tuple on the right are 'unpacked' into the variables/names on the left:
>>>(rno,name,place,pin)=stud
>>> rno
101
>>> name
'shilpa'
>>> place
'kayamkulam'
>>> pin
690535
Tuple packing and unpacking
Tuples are used to group data. In tuple packing, the values on the right are ‘packed’ together in a tuple:
>>>stud=(101,'shilpa','kayamkulam',690535) In tuple unpacking, the values in a tuple on the right are 'unpacked' into the variables/names on the left:
>>>(rno,name,place,pin)=stud
>>> rno
101
>>> name
'shilpa'
>>> place
'kayamkulam'
>>> pin
690535
Tuple assignments
Once in a while, it is useful to swap the values of two variables. With conventional assignment statements, we have to use a temporary variable. For example, to swap a and b:
temp = a
a = b
b = temp
Tuple assignment solves this problem neatly:
(a, b) = (b, a)
a = b
b = temp
Tuple assignment solves this problem neatly:
(a, b) = (b, a)
The left side is a tuple of variables; the right side is a tuple of values. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments. This feature makes tuple assignment quite versatile.
Naturally, the number of variables on the left and the number of values on the right have to be the same:
We can swap values of two tuples>>>t1=(10,20,30)
>>>t2=(100,200)
>>>t2,t1=t1,t2
>>>t1
(100,200)
>>>t2
(10,20,30)
Converting lists into tuples and tuples into lists
>>>L=[10,20,30,40]
>>>T=tuple(L)
>>>T
(10,20,30,40)
>>> T=(10,20,30)
>>> L=list(T)
>>> L
[10, 20, 30]
tuples will take less memory
import sys
t=(1,2,3)
l=[1,2,3]
print(sys.getsizeof(t))
print(sys.getsizeof(l))
output:
32
40
tuples will take less time
from timeit import timeit
t1=timeit("list([1,2,3])",number=10000000)
print(t1)
t2=timeit("tuple((1,2,3))",number=10000000)
print(t2)
output:
3.172022018001371 1.4471702060000098
Program to read numbers and find minimum, maximum and sum using Tuple
n=int(input("Enter how many numbers...."))
print("Enter {} numbers".format(n))
t=tuple()
for i in range(n):
x=int(input())
t=t+(x,)
print("minimum=",min(t))
print("maximum=",max(t))
print("sum=",sum(t))
Write a menu driven program to store the students details(rno,name,mark) as a list of tuples.The menu has the following options ( university question)
add-adding students details
remove-remove the details by giving roll number
search-search and display the details by giving roll number
max-display the details of the students with highest mark
stud=[]
while True:
print("1.add\n2.remove\n3.search\n4.max\n5.Display\n6.Exit")
op=int(input("Enter option...."))
if op==1:
print("Enter the students details..")
rno=int(input("enter roll number..."))
name=input("enter name..")
mark=int(input("enter mark.."))
stud.append((rno,name,mark))
print(stud)
if op==2:
rno=int(input("Enter the rollnumber to remove"))
stud=filter(lambda x:x[0]!=rno,stud)
if op==3:
rno=int(input("Enter the roll number to search"))
s=filter(lambda x:x[0]==rno,stud)
for i in s:
print(i)
if op==4:
stud=sorted(stud,key=lambda x:x[2],reverse=True)
print(stud[0])
if op==5:
print("Students Details")
for i in stud:
print(i)
if op==6:
print("Bye")
break
Comments
Post a Comment