HOW TO USE TUPLE IN PYTHON?


TUPLE

A Tuple is an ordered and unchangeable collection of python objects, each object is separated by a comma and the whole set is enclosed by parenthesis. Tuples allow duplicate values.

Properties of TUPLE

Tuple items or objects are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has an index [0], the second item has an index [1], etc.

The items of a tuple are arbitrary Python objects. Tuples of two or more items are formed by comma-separated lists of expressions.

s = ('ABC', 100, 2.5)

Sometimes the () is omitted in the syntax.

s = 'ABC', 100, 2.5

A tuple of one item (a ‘singleton’) can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions).

t2 = ('ABC', )        # A 1-item tuple

An empty tuple can be formed by an empty pair of parentheses.

t1 = ()                # An empty tuple
Tuple Unpacking

To use the tuple elsewhere, you can unpack its parts into variables.

name, quantity, price = s
print('Cost', quantity * price)

The number of variables on the left must match the tuple structure.

name, quantity = s     # ERROR
Traceback (most recent call last):
...
ValueError: too many values to unpack
TUPLE CONSTRUCTOR

tuple()
It is also possible to use the tuple() constructor to make a tuple.

Example
Using the tuple() method to make a tuple:

Code

fruits = tuple(("apple", "banana", "cherry")) 
print(fruits)

Output

('apple', 'banana', 'cherry')
Multiply Tuples

If you want to multiply the content of a tuple a given number of times, you can use the * operator:

Example
Multiply the fruits tuple by 2:

Code

fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)

Output

('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')
Tuple Methods

Python has two built-in methods that you can use on tuples.

MethodDescription
count()Returns the number of times a specified value occurs in a tuple
index()Searches the tuple for a specified value and returns the position of where it was found
How to use count() in Python?

Code

a = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = a.count(5) #returns no. of times 5 occurs in tuple a
print(x)

Output

2
How to use index() in python?

The index() method finds the first occurrence of the specified value.

The index() method raises an exception if the value is not found.

Code

#Search for the first occurrence of the value 7, and return its position:

a = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = a.index(7)
print(x)

Output

2
Difference between Tuple and List

The difference between a tuple and a list is that a tuple is immutable whereas a list is mutable. We can store any type of data in Tuple.

Example of Tuple Syntax in Python-

Code
a=(5,10)                  #values in the tuple are surrounded by parenthesis ()
print(a)                    #tuple is a collection of values
b=(1,2.50,”hello”)   #tuple as collection of different types of values
print(b)                   #print tuple
print(b[1])               #provide the value of 2nd element having index 1
print(len(b))           #provide the length
print(b[0:2])           #slice the tuple
Output
(5, 10)
(1, 2.5, ‘hello’)
2.5
3
(1, 2.5)

Example of Immutability of Tuple-

b=(1,2.50,”hello”)

b[1]=4.50        #it will show error, as tuples are immutable

Example of type casting and concatenation of Tuple-

Code
list1=[1,3.5,”hello”]   #variable of list type
list2=[4,2.1,8]         #variable of list type
print(list1)           #printing variable list1
print(type(list1))
tuple1=tuple(list1)    #type casting of list variable to tuple
tuple2=tuple(list2)    #type casting of list variable to tuple
print(type(tuple1))    
ctup=tuple1+tuple2  #concatinating tuple variables
print(ctup)
print(ctup[3])           #print 4th element,its immutable so ctup[3]=5 gives error
a=(4)                   #it will be treated as expression having int value
print(type(a))           #value of a is enclosed in () but missing comma
a=(4,)                   #a singleton tuple is defined by adding comma as suffix
print(type(a))
Output
[1, 3.5, ‘hello’]
<class ‘list’>
<class ‘tuple’>
(1, 3.5, ‘hello’, 4, 2.1, 8)
4
<class ‘int’>
<class ‘tuple’>

Leave a Reply

Your email address will not be published. Required fields are marked *