You are on page 1of 3

OPERATIONS OF TUPLE

Tuple:
A tuple is a collection of objects which ordered and immutable. Tuples are sequences,
just like lists. The differences between tuples and lists are, the tuples cannot be
changed unlike lists and tuples use parentheses, whereas lists use square brackets.

Creating a Tuple :
Creating a tuple is as simple as putting different comma-separated values.
T=( 1,55,”Baby",a12);

Empty Tuple :
The empty tuple is written as two parentheses containing nothing
T=( );

To write a tuple containing a single value you have to include a comma, even though there is only one
value .
T= (77,);
Concatenation of Tuples: (Addition)
Concatenation of tuple is the process of joining two or more Tuples. Concatenation is done
by the use of ‘+’ operator.

• Only the same datatypes can be combined with concatenation, an error arises if a list
and a tuple are combined.
Ex:
T1 =(1,2,3);
T2=(4,5,6);
Print(T1+T2);
Output
(1,2,3,4,5,6)

Check if an Item Exists in the Python Tuple: (Membership Operator)


in keyword, can not only be used with tuples, but also with strings and lists too. It is used to
check, if any element is present in the sequence or not. It returns True if the element is found,
otherwise False. For example,
>>> t = (1, 2, 3, 6, 7, 8)
>>> 2 in t
>>> 5 in t

Output
True
False

Repetition:( Multiplication)
Multiplying a tuple by any integer, x will simply create another tuple with all the elements
from the first tuple being repeated x number of times. For example, t*3 means, elements of
tuple t will be repeated 3 times.
>>> t = (2, 5)
>>> print (t*3);
Output
(2,5,2,5,2,5)

Iterating through a Tuple in Python

We can use the for loop to iterate over the elements of a tuple. For example,
languages = ('Python', 'Swift', 'C++')

# iterating through the tuple


for language in languages:
print(language)

Output
Python
Swift
C++

max() and min() function:


To find the maximum value in a tuple, we can use the max() function, while for finding the
minimum value, min() function can be used.

>>> t = (1, 4, 2, 7, 3, 9)

>>> print (max(t))

>>> print (min(t))

Output

Advantages of Tuple over List in Python

• We generally use tuples for heterogeneous (different) data types and lists for
homogeneous (similar) data types.

• Since tuples are immutable, iterating through a tuple is faster than with a list. So there
is a slight performance boost.

• Tuples that contain immutable elements can be used as a key for a dictionary. With
lists, this is not possible.

• If you have data that doesn't change, implementing it as tuple will guarantee that it
remains write-protected

You might also like