Skip to main content

Tuple in Python

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.
Where is the benefit of tuples?
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.

The following example shows how to define a tuple and how to access a tuple. 
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
>>> t = ("tuples", "are", "immutable")
>>> t[0]
'tuples'
>>> 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

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'>
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
>>>min(a)
10
>>>max(a)
30
>>>sum(a)
60
>>>len(a)
3
>>>a.index(20)
1
>>>c.count(30)
2
cmp( )
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
since the tuples are immutable you cannot sort the tuple.However you can use the sequence function sorted() to create a new sorted tuple.
>>>sorted(a)
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) 
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 tuples into lists and lists into tuples
>>>L=[10,20,30,40]
>>>T=tuple(L)
>>>T
(10,20,30,40)
>>> T=(10,20,30)
>>> L=list(T)
>>> L
[10, 20, 30]
Sample Program
Program to read numbers and find minimum, maximum and sum using Tuple
n=input("Enter how many numbers....")
print "Enter {} numbers".format(n)
t=tuple()
for i in range(n):
   x=input()
    t=t+(x,)
print "minimum=",min(t)
print "maximum=",max(t)
print "sum=",sum(t)
Now you can try following programs using tuple
1.Read ‘n’ numbers and find their sum,average,min,max and also print a sorted list.
2.Read two tuples and exchange their values.
3.Find the variance and standard deviation of ‘n’ numbers.
4.Check the number of occurrence of an element in a tuple.
5.Find the positions of occurrences(indices) of an element in a tuple.

Comments

Post a Comment

Popular posts from this blog

Classes and Objects in Python

Python is an object-oriented programming language, which means that it provides features that support object-oriented programming. The basic components of object oriented programming are classes and objects. A Class is a blue print to create an object. It provides the definition of basic attributes and functions of objects. Object is a running instance of the class having the identity(name), properties( values) and behaviors(functions). The Object oriented program thus consist of object definitions (classes) and most of the computations and functions are mentioned as operations on the object. Each object definition corresponds to some object or concept in the real world, and the functions that operate on these object correspond to the ways real-world objects interact. We have learned objects of string, list, tuple etc…and used the properties and functionalities of these objects which are built into the Python. Now we are going to create our own(user defined) objects. Th

Identifiers,Variables and Keywords

Identifiers An identifier is a name given to entities like variables,functions,class, functions etc. It helps to differentiate one entity from another. Rules for writing identifiers 1.Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _.  Names like myClass, var_1 and print_this_to_screen, all are valid example. 2.An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name. 3.Keywords cannot be used as identifiers. Eg: global = 1 is invalid 4.We cannot use special symbols like !, @, #, $, % etc. in our identifier. a@=0 is invalid 5.An identifier can be of any length. Things to Remember Python is a case-sensitive language. This means, Variable and variable are not the same. Always give the identifiers a name that makes sense. While c = 10 is a valid name, writing count=10 would make more sense, and it would be easier to figure out what it represents when you look at your code after

Files in Python , Exception handling

While a program is running, its data is in main memory. When the program ends, or the computer shuts down, data in memory disappears. To store data permanently, you have to put it in a file. Files are usually stored on a secondary storage device(hard disk, pen drive, DVD,CD etc).  When there are a large number of files, they are often organized into directories (also called “folders”). Each file is identified by a unique name, or a combination of a file name and a directory name.  By reading and writing files, programs can exchange information with each other and generate printable formats like PDF. Working with files is a lot like working with books. To use a book, you have to open it. When you’re done, you have to close it. While the book is open, you can either write in it or read from it. In either case, you know where you are in the book. Most of the time, you read the whole book in its natural order, but you can also skip around. All of this applies to files as well.