XI CS: Tuple

INTRODUCTION:  

  • a Tuple in Python is represented as a list of values separated with commas enclosed within parentheses ( round brackets). It can store values of any data type.
  • For example, (“mango”, “apple”, “dragon fruit”, ” grapes “) is a tuple.

Features of Python Tuple:

  • The tuple is an immutable data type i.e, Tuples are not modifiable, hence we can not change the elements of the tuple, once created.
  • Tuples are ordered sequence which means that all the elements have a defined order, and that order will not change.
  • Tuples allow duplicate value. Because of indexing two elements can have same value.
  • Tuple are iterable.

How to create a tuple in Python?

In order to create a Python Tuple, put your elements in round brackets (). The round bracket indicates the start and end of the tuple list.

For example (12, 34, 56), ( “apple”, ” mango”, “orange”)

In the simplest form, we can create a tuple in the following way:

Tuple= ( )

tpl= (value1, value2,....)

#This is called tuple display construct

Types of the Python Tuple:

In python, we can have empty, single, long, or nested tuples

1 Empty Tuple: The tuple that has no elements enclosed in the bracket. It has Truth value as False. 

For example: 

  • T = ( ) # Empty tuple
  • tuple1 = ()
  • print(tuple1)
  • #Output
  • ( )

2. Single Tuple: A python tuple that contains only one single element is called a Single tuple in Python. 

For example, 

  • Tuple2=(1) # Single tuple
  • tuple2 = (1)
  • print(tuple2)
  • #Output
  • (1)

3. Long Tuple: A Python tuple that contains many elements and splits into several lines. 

For Example 

(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30)

#Long tuple

  • tuple3= (1,2,3, 4, 5, 6, 7, 8,9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25)
  • print(tuple3)
  • #Output
  • (1,2,3, 4, 5, 6, 7, 8,9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25)

4. Nested Tuple: If a tuple contains another tuple as an element then it is called a Nested Tuple in Python. 

For example: (1, 2, [3, 4, 5], 6, (“apple”, “mango”)) # nested tuple

  • tuple4 =(1, 2, [3, 4, 5], 6, ("apple", "mango")) 
  • print(tuple4)
  • #Output
  • (1, 2, [3, 4, 5], 6, ("apple", "mango")) 

Indexing of Tuple in Python

In order to access the elements of any sequence like a list or tuple, Python offers indexing. Every element in the tuple has an index value using which we can access them.

Indexing of Tuple in Python

1. Forward Indexing:

The index begins from 0 to length -1 in forward direction. 

For example, (12, 34, 56) have indices from 0 to 2.


2. Negative Indexing:

Whereas in the backward direction, the indexing is from -1 to -length of the List.

For example, Tuple1=(12, 34, 56, 78, 90)

In this Tuple, 12 has 0 indexes in forward direction and a -5 index in the backward direction.

#Note: If you try to access an index outside of the tuple index range will raise an IndexError.

Slicing of Tuple

The slicing operator is used for accessing a range of elements i.e., a slice from the whole tuple.

The tuple slicing returns a slice or part of the tuple from the given index range x to y. (x is included but y is not included).

The syntax of the list slicing is: Tuple [ start: stop]

#Note: If the start and stop index is out of the bound list then an empty list is returned.

tuple1= (1,2,3,4, 5, 6, 7, 8, 9, 10, 11) # acessing a single element

print(tuple1[4])              #acessing a range of element

output: 5

x= tuple1[1: 4]

print(x)

Output:   (2,3,4)

print(tuple1[11:15])

Output: ()

print(tuple1[ : ])  #slicing from begining to end

#Output

(1,2,3,4, 5, 6, 7, 8, 9, 10, 11)

Length of a Python Tuple

The tuple length is equal to the number of elements in the list. In order to determine the length of the tuple, we use len() function.

#Length of the tuple

tuple1= ( "apple", " mango", "orange")

#nested tuple

tuple2 =(1, 2, [3, 4, 5], 6, ("apple", "mango"))

print(len(tuple1))

print(len(tuple2))

#Output

  • 3
  • 5

Tuple Operations in Python

It is the computation or actions applied to the variable containing tuple data types in an expression.

Like List manipulation, Tuple manipulation in Python can be done using various operators like concatenation (+), repetition (*), slicing of the tuple, and membership operators( in /not in). So, Let’s understand each operator in brief.

1. + Concatenation

2. * Repetition

3. >, <, ==, != Comparison operator

4. in, not in Membership operator

5. [ a: b] Slicing


List operators in python

1. Concatenation operator (+)

The (+) operator is used to add to two tuples.

The syntax of the given operation is: Tuple1+Tuple2

#Note: The operands must be on tuples. In other words, only a tuple should be added to another tuple. If any other data type is added to a tuple using the (+) operator, then it will result in an error.

t1=(12, 34, 56)

t2=(78, 90)

print(t1+t2)

t3=(23, 45, 67)

t=t1 +t2 +t3

print(t)

#Output

  • (12, 34, 56, 78, 90)
  • (12, 34, 56, 78, 90, 23, 45, 67)

2. Repetition operator (*)

Like string and list, (*) operator replicates the element of the tuple of specified times.

The syntax of the given operation: Tuple*n

t1=(12, 34, 56)

print( t1*3)

#Output

  • (12, 34, 56, 12, 34, 56, 12, 34, 56)

3. Comparison Operator

Python offers standard comparison operators like ==,<, >, != to compare two lists.

For comparison, two tuples must-have elements of comparable types, otherwise, you will get an error.

Python gives the result of comparison operators as True or False and moreover, it compares tuple list element by element. It compares the first element if they are the same then will move to the next, and so on.

Examples of a comparison list operator:

Comparison                 Result Reason

(12, 3, 4 , 0) > (9, 12, 3) True compared the first element of both the list, hence returning True

(3, 4, 8, 7) > (3, 4, 9, 8) False The first elements were the same so, the compared third element, hence return False.

(1, 2, 3, 4)==(1, 2, 3, 4) True compares every element and found the same, hence returning True


4. Membership Operator (in, not in)

The membership operator checks whether an element exists in the given tuple sequence.

in: Return True if an element exists in the given tuple; False otherwise

not in: Return True if an element does not exist in the given tuple; False otherwise.

t1=(12, 34, 56, 78, 90) #membership operator

56 in t1

12 not in t1

t2=("a", "b", "c", "d")

"c" in t2

#Output

  • True
  • False
  • True

5. Tuple Slicing

Tuple slicing returns a slice or part of the tuple list from the given index range x to y. (x is included but y is not included).

The syntax of the tuple slicing is: Tuple[ start: stop]

#Note: If the start and stop index is out of the bound list then an empty tuple is returned.

t1= (12, 34, 56, 78, 90)

x= t1[1:4]

print(x)

print(t1[8:10])

#Output

  • (34, 56, 78)
  • ( )

Iterating through the Tuple

Like string and list, We can also iterate or traverse through tuples. Using for loop we can iterate the elements of the tuple in Python.

t1=(" apple", "mango", "orange", " grapes") #traversing a tuple

for x in t1:

      print(t1[x])

#Output

  • apple
  • mango
  • orange
  • grapes

Deleting a Tuple

You may wonder can we delete a tuple once it is created? Yes! Although a tuple is immutable and we cannot change but we can delete it.

We can delete the whole tuple sequence with del() function.

tuple1=(" apple", "mango", "orange")

del(tuple1)

1. Create empty tuple

We can use the tuple() method to create an empty tuple.

t1=tuple( )

print(t1)

#Output

( )

2. Convert list into Tuple

In order to convert the list into a tuple, the tuple() method is used. The list is passed as an argument in the tuple().

list1=[12,34,56]

t1= tuple( list1)

print(t1)

#Output

(12,34, 56)

3. Convert string into the tuple

In order to convert the string into a tuple, the tuple() method is used. The string is passed as an argument in the tuple().

string1= "apple"

t1= tuple(string1)

print(t1)

#Output

("a", "p", "p", "l", "e")

4. Convert dictionary into a tuple

In order to convert the dictionary into a tuple, the tuple() method is used. The dictionary is passed as an argument in the tuple(). The tuple will only have all the keys of the key: value pairs of the dictionary.

dict= { 1:"a", 2: "b", 3 :"c"}

t1= tuple( dict)

print(t1)

#Output

(1, 2, 3)

Unpacking of Tuple

Although Python Tuple is immutable, still we can use the element of the list. We can do so by unpacking Tuple.

When we create a tuple we assign different values to Tuple as elements. This is called the packing of Tuples. Unpacking is the reverse of it. It means getting elements of Python Tuple.

#packing of tuple

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

#unpacking of tuple

a, b, c, d, e, f = t1

print(a)

print(b)

print(c)

print(d)

print(e)

#Output

1

2

3

4


Tuple Methods and Built-in Functions at a glance


Function/Method Name

Description

Example

len(tuple)

Returns number of elements in given tuple.

>>> t=(10,20,30,40,50,90,100)

>>>len(t) 7

tuple()

Creates an empty tuple if no argument

is passed

 

 

Creates a tuple if a sequence is passed as argument

>>> t1 = tuple()

>>> t1 ( )

>>> t2 = tuple('aeiou')#string

>>> t2

('a', 'e', 'i', 'o', 'u')

>>> t3 = tuple([1,2,3]) #list

>>> t3 (1, 2, 3)

>>> t4 = tuple(range(5))

>>> t4

(0, 1, 2, 3, 4)

count (<item>)

It will count and return number of occurrences of the passed element.

>>> t.count(10) 1

>>> t.count(200) 0

index(<item>)

Returns the index of the first occurrence of the element in the given tuple

>>> tuple1 = (10,20,30,40,50)

>>> tuple1.index(30) 2

>>> tuple1.index(90) ValueError: tuple.index(x): x not

in tuple

sorted()

Takes elements in the tuple and returns a new sorted list. It should

be noted that, sorted() does not make any change to the original tuple

>>> t1 = (10,100,50,60,30,40)

>>> sorted(t1)

 

[10, 30, 40, 50, 60, 100]

min()

Returns minimum or smallest element of the tuple

>>> tuple1 = (19,12,56,18,9,87,34)

>>> min(tuple1)

9

max()

Returns maximum or largest   element of the tuple.

 

>>> max(tuple1)

87

sum()

Returns sum of the elements of the Tuple

>>> sum(tuple1)

235


Exercise Questions:    Tuple

1 Mark Questions

Sr.

Question

Answer

1.

What will be the output of the following code:

Employee=(‘rajesh’,100,23,[1,2,3])

len(Employee)

   4

2.

How tuple is different from list?

 The tuples are immutable  sequences  while lists are mutable. The  lists can shrink or grow while tuples cannot.

3.

Which of the following creates a tuple? (a)t1=("a","b") (b) t1[2]=("a","b")

(c) t1=(5)*2 (d) None of the above

(a)t1=(“a”,”b”)

4.

What is the length of the tuple shown below:

T = ( ( ( ( ‘a’, 1 ), ’b’ , ’c’ ), ’d’ , 2 ) , ’e’ , 3 )

 3

5.

What is the difference between (30) and (30,)?

When we use type function then (30) is type of 'int' class where (30,) is a type of tuple which contain one element.

2 Mark Questions

Sr.

Question

Answer

1.

Write a python program to create tuple of 10 integer type elements and find the largest element in tuple.

tuple=(6,3,1,8,4,9,2,20)

M=max(tuple)

print("Largest Value in Tuple: ",M)

2.

t1 = (3, 4)

t2 = ('3', '4')

print(t1 + t2)

(3, 4, '3', '4')

3.

t2 = (4, 5, 6)

t3 = (6, 7)

t4 = t3 + t2 t5 = t2 + t3 print(t4) print(t5)

(6, 7, 4, 5, 6)

(4, 5, 6, 6, 7)

4.

Discuss the utility and significance of Tuples, briefly.

It is a type of arrays . it play very important role in python . in python it is immutable type of container which store any kind of data types it is short

in memory size in comparison of list .

5.

Does the slice operator always produce a new tuple ?

No ,it will print a part of tuple .

6.

Lists and Tuples are ordered.

Explain.

Lists and Tuples are ordered sequences as each element has a fixed position.


3 Mark Questions

Sr.

Question

Answer

1.

Find the output of the following Python Code: t=(10,20,30,40,50,60,70,20,30,50)

>>> print (t)

>>> print (max(t))

>>> print (t.count(20))

>>> print (t[0]+5)

>>> print (t.index(40))

>>> print (min(t) + len(t))

(10, 20, 30, 40, 50, 60, 70, 20, 30, 50)

70

2

15

3

20

2.

Write a program that inputs two tuples and creates a third, that contains all elements of the first followed by all

elements of the second.

tup1 = eval(input("Enter First tuple :-")) tup2 = eval(input("Enter second tuple :-")) tup3 = tup1 + tup2

print(tup3)

3.

Create a tuple names as given here: names = ('jai', 'rahul', 'maya', 'kia', 'Dav', 'Lalit')

Write proper code for getting :

(a)  ('maya', 'kia', 'Dav')

(b)  ('jai')

(c)  ('kia', 'Dav', 'Lalit')

a) names [2 : 5 ]

 

(b)  names [ 0 ]

 

(c)  names [3 : ]

4.

TypeError occurs while statement 2 is running. Give reason. How can it be corrected?

>>> tuple1 = (5)      #statement 1

>>> len(tuple1)       #statement 2

Because tuple1 is integer not a tuple. So, we cannot find the length of integer.

If you want to make tuple then you should write ( 5, )

4 Mark Questions

Sr.

Question

Answer

1.

What will be stored in variables a, b, c, d, e, f, g, h after following statements?

perc = (88, 85, 80, 88, 83, 86)

a = perc[2:2] b = perc[2:] c = perc[:2] d = perc[:-2] e = perc[-2]

f = perc[2:-2]

g = perc[-2:2]

h = perc[:]

()

(80, 88, 83, 86)

(88, 85)

(88, 85, 80, 88)

83

(80, 88) ()

(88, 85, 80, 88, 83, 86)


2.

Write a program to input n numbers from the user. Store these numbers in a tuple. Print the maximum and minimum number from this tuple.

tup= () while True:

n = int(input("Enter a number :- "))   

tup += (n,)

ch = input("To quit enter y/Y =") if ch == "y" or ch=="Y":

print(tup) print("Max :-",max ( tup ))

print("Min :-",min ( tup ))     

break

3.

Consider the following tuples, tuple1 and tuple2 and find the output of the following statements:

 

tuple1 = (23,1,45,67,45,9,55,45)

tuple2 = (100,200)

i.  print(tuple1.index(45))

ii.  print(tuple1.count(45))

iii.  print(tuple1 + tuple2)

iv.  print(len(tuple2))

v.  print(max(tuple1)) vi print(min(tuple1))

vii.  print(sum(tuple2))

viii.   print( sorted ( tuple1 ) ) ix.print(tuple1)



I.            2


II.             3


III.      (23, 1, 45, 67, 45, 9, 55, 45, 100, 200)


IV.            2


V.            67


VI.            1


VII.            300


VIII.      [1, 9, 23, 45, 45, 45, 55, 67]


IX.      (23, 1, 45, 67, 45, 9, 55, 45)

4.

Write a program to input names of n students and store them in a tuple. Also, input a name from the user and find if this student is present in the tuple or not.

We can accomplish these by:

(a)  Writing a user defined function

(b)  Using the built-in function

def find( name):

if name in tup :

return name, "is present in ",tup 

else :

return name, "is not present in ",tup

 

tup = eval( input ("Enter a tuple containing name of student :-"))

nam = input("Enter name of student :-") print( find( nam ) )

FAQ :

1.What is the difference between eval () and int () function in Python?

When considering the int() function, we can convert any string integers only in to integers. If you input any floating point number, you'll have a value error after execution. But when considering eval() function, we can use it to convert any string containing a python function or number or mathematical expression.

2. What is the difference between input and eval?

When taking the user's input, if the user enters an integer input, the input function returns a string. The eval() function, however, evaluates the string as an expression and returns the result of that evaluation.

3. What is any () function used in Tuples?

any() function returns True if a tuple is having at least one item. if the tuple is empty it will return False. 

Example:

a=(1,)
print(any(a))
True
b=()
print(any(b))
False

Conclusion

Python provides various data types with different functions that make coding in python quite easier. Similarly, Python Tuple makes code more efficient, easier, and moreover, easy to understand through its various functions and operations.

**********************

No comments:

Post a Comment