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.

Popular posts from this blog

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. To open a fil…

User Defined Functions in Python

So far we have only seen the functions which come with Python either in some file (module) or in interpreter itself (built in), but it is also possible for programmer to write their own function(s) and are called User Defined Functions. These functions can then be combined to form a module which can then be used in other programs by importing them.
In the context of programming, a function is a named sequence of statements that performs a desired operation. This operation is specified in a function definition.
To define a function keyword def is used. After the keyword comes an identifier i.e.name of the function, followed by parenthesized list of parameters and the colon which ends up the line. Next follows the block of statement(s) that are the part of function. A block is one or more lines of code, grouped together so that they are treated as one big sequence of statements while executing. In Python, statements in a block are written with indentation. Usually, a block begins when a li…

Dictionary In Python

Dictionaries are similar to other compound types except that they can use any immutable type as an index. We can refer to a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps a value. The association of a key and a value is called a key-value pair. A dictionary is an extremely useful data storage construct for storing and retrieving all key value pairs, where each element is accessed (or indexed) by a unique key. However, dictionary keys are not in sequences.
            Dictionaries are mutable.             Dictionaries are unordered. Items in dictionaries are accessed via keys and not via their position. A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated (or mapped) to a value. The values of a dictionary can be any Python data type. So dictionaries are unordered key-value-pairs.  Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and…