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]
>>> 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

Tuple operations are similar to list

>>>10 in a
>>>100 not in a

Tuple Functions

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.
since the tuples are immutable you cannot sort the tuple.However you can use the sequence function sorted() to create a new sorted tuple.
Tuple packing and unpacking
tuples are used to group data. In tuple packing, the values on the right are ‘packed’ together in a tuple:
In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the variables/names on the left:
>>> rno
>>> name
>>> place
>>> pin

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

Converting tuples into lists and lists into tuples
>>> 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)
for i in range(n):
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

Strings in Python

Strings are compound data type made of sequence of characters. Hence from the string, the individual charters can also be directly accessed. Strings are created by using single quotes or double quotes or triple quotes.
Example: >>>s1="Python Programming" >>>s2='Python Programs' >>>s3="""Python is a powerful Programming language"""
This will create a string object s1, s2 and s3 using different forms.
Individual characters can be accessed using different subscripts( +ve or –ve) with the string object.
Example >>>s="Python" >>>s[0] ‘P’ >>>s[2] ‘t’ >>>s[5] ‘n’ >>>s[-1] ‘n’ >>>s[-3] ‘h’ >>>s[-6] ‘P’
We can also slice a string. Segment of a string is called a slice.
>>>s[1:3] ‘yt’
If the first index is not mentioned, the slicing will start from 0. >>>s[:3] ‘Pyt’
>>>s[2:6] ‘thon’
If the last index is not mentioned, the slicing will go till the end o…

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 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…

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…