Tuples - Python Programming Made Easy (2016)

Python Programming Made Easy (2016)

Chapter 8: Tuples

A tuple is a sequence of values, which can be of any type and they are indexed by

integer. Tuples are just like list, but we can’t change values of tuples in place. Thus tuples are immutable. The index value of tuple starts from 0.

Tuple Creation

A tuple consists of a number of values separated by commas.

Ex 8.1:Tuple creation

tup1 = ('desktop', 'laptop', 1997, 2000)

tup2 = (1, 2, 3, 4, 5 )

tup3 = "a", "b", "c", "d"

print tup1

print tup2

print tup3

But in the result, same tuple is printed using parentheses. To create a tuple with single element, we have to use final comma. A value with in the parenthesis is not tuple.

The empty tuple is written as two parentheses containing nothing:

tup1 = ()

To write a tuple containing a single value we have to include a comma, even though there is only one value:

tup1 = (50,);

Example 8.2: Create tuples with single character.

T=('P','Y','T','H','O','N')

print T

Another way of creating tuple is built-in function tuple ().

T=tuple()

print T

Fig 8.1: creating tuple using built-in function

Tuple insertion

We can add new element to tuple using + operator.

t=(1,2,3,4)

t+(5,) # this will not create modification of t.

print t

t=t+(5,) # this will do modification of t.

print t

Fig 8.2: Tuple insertion

Example 8.3: Write a program to input ‘n’ numbers and store it in tuple.

t=tuple()

n=input("Enter count of numbers")

print " enter all numbers one after other"

for i in range(n):

a=input("enter number")

t=t+(a,)

print "output is"

for i in range(n):

print t[i]

We can also add new element to tuple by using list. For that we have to convert the tuple into a list first and then use append() function to add new elements to the list. After completing the addition, convert the list into tuple.

Example 8.4: Add new elements to tuple using a list.

T=tuple() #create empty tuple

l=list(T) #convert tuple into list

l.append(11) #Add new elements to list

l.append(22)

T=tuple(l) #convert list into tuple

print T

Tuple initialization

We can initialize a tuple as follows

T=(0,)*5

print T

Fig 8.3: Tuple initialization

Tuple Assignment

If we want to interchange (swap) any two variable values, we have to use temporary variable. But in python, tuple assignment is more elegant.

T1=(10,20,30)

T2=(100,200,300,400)

T1,T2=T2,T1 # swap T1 and T2

print T1

print T2

Fig 8.4: Tuple assignment

The left side is a tuple of variables, while the right side is a tuple of expressions. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments. The number of variables on the left and the number of values on the right have to be the same.

T1=(10,20,30)

T2=(100,200,300)

T3=(1000,2000,3000)

T1,T2=T2,T1,T3

Fig 8.5: Tuple assignment error

Here, two tuples are in the left side and three tuples are in right side. That is why, we get errors. Thus, it is required to have same number of tuples in both sides to get the correct result.

Tuple Slices

Slice operator works on Tuple also. This is used to display more than one selected value on the output screen. Slices are treated as boundaries and the result will contain all the elements between boundaries.

Syntax: Seq = T [start: stop: step]

Where start, stop & step all three are optional. If we omit first index, slice starts from ‘0’. On omitting stop, slice will take it to end. Default value of step is 1.

T=(1,2,3,4,5)

print T

T1=T[2:4]

print "T[2:4] =", T1

print "T[:]=", T[:] # Will produce a copy of the whole tuple.

print "T[::2]=", T[::2] # Will produce a Tuple with every alternate element.

print "T[:3]=",T[:3] # Will produce 0 to 2(3-1)

print "T[2:]=",T[2:] # Will produce from 2 to end.

Fig 8.6: Tuple slice

Updating Tuples

Tuples are immutable which means you cannot update them or change values of tuple elements.

tup1[0] = 100; # Invalid

But we able to take portions of an existing tuples to create a new tuples as follows.

tup1 = (12, 34.56);

tup2 = ('abc', 'xyz');

tup3 = tup1 + tup2;

print tup3;

Fig 8.7: Tuple updation

Delete Tuple Elements

It is not possible to remove individual tuple elements. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded. To explicitly remove an entire tuple, just use the del statement.

T=(1,2,3,4,5)

print T

del T

print T

Fig 8.8: Tuple deletion

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.

Description

Python Expression

Results

Length

len((1, 2, 3))

3

Concatenation

(1, 2, 3) + (4, 5, 6)

(1, 2, 3, 4, 5, 6)

Repetition

['Hello!'] * 4

(''Hello!', ''Hello!', ''Hello!', ''Hello!')

Membership

1 in (1, 2, 3)

True

Iteration

for x in (1, 2, 3):

print x,

1 2 3

Table 8.1: Tuple operations

Built-in Tuple Functions

Python includes the following tuple functions

S.No

Function

Description

Example

1

cmp(tuple1, tuple2)

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.

tuple1 = (11,22,33,44,55)

tuple2 = (111,222,333,444,555)

print cmp(tuple1, tuple2)

>> -1

2

len(tuple)

It returns the number of items in a tuple.

print len(tuple1)

>>5

3

max(tuple)

It returns its largest item in the tuple.

print max(tuple1)

>>55

4

min(tuple)

It returns its smallest item in the tuple.

print min(tuple1)

>>11

5

tuple(seq)

Converts a list into tuple.

seq = [1,2,3,4,5]

print tuple(seq)

>>(1, 2, 3, 4, 5)

Table 8.2: Tuple built-in functions

Solved Programs

1. Write a program to input 5 subject names and put it in tuple and display that tuple information on the output screen.

Ans:

t=tuple()

print " Enter 5 courses";

for i in range(5):

a=raw_input("Enter course name")

t=t+(a,)

print "output is"

print t

2. Write a program to input any two tuples and interchange the tuple values.

Ans:

t1=tuple()

n=input("Total number of values in first tuple")

for i in range(n):

a=input("enter elements")

t1=t1+(a,)

t2=tuple()

m=input("Total number of values in first tuple")

for i in range(m):

a=input("enter elements")

t2=t2+(a,)

print "First Tuple"

print t1

print "Second Tuple"

print t2

t1,t2=t2,t1

print "AFTER SWAPPING"

print "First Tuple"

print t1

print "Second Tuple"

print t2

Practice Problems

1. Write a program to input ‘n’ employees’ salary and find minimum & maximum salary among ‘n’ employees.

2. Write the output from the following codes;

(i) t=(10,20,30,40,50)

print len(t)

(ii) t=('a','b','c','A','B')

max(t)

min(t)

(iii) T1=(10,20,30,40,50)

T2 =(10,20,30,40,50)

T3 =(100,200,300)

cmp(T1,T2)

cmp(T2,T3)

cmp(T3,T1)

(iv) t=tuple()

Len(t)

(iv) T1=(10,20,30,40,50)

T2=(100,200,300)

T3=T1+T2

print T3

3. Write a program to input two set values and store it in tuples and also do the comparison.

4. Find the errors from the following code:

t=tuple{}

n=input(Total number of values in tuple)

for i in range(n)

a=input("enter elements")

t=t+(a)

print "maximum value=",max(t)

print "minimum value=",min(t)

5. Write a program to input ‘n’ numbers and separate the tuple in the following manner.

Example

T=(10,20,30,40,50,60)

T1 =(10,30,50)

T2=(20,40,60)

6. Find the output from the following code:

T=(10,30,2,50,5,6,100,65)

print max(T)

print min(T)

7. Find the output from the following code:

t=tuple()

t = t +(PYTHON,)

print t

print len(t)

t1=(10,20,30)

print len(t1)