Tuples in Python Examples

Tuples in Python Examples

A tuple is a  popular data structure in python just like the list which contains a sequence of elements separated by commas and is enclosed in parenthesis. Tuples are immutable which means we cannot modify or change the element from the tuple. Tuples are faster than lists and are of sequence type. tuples index starts from 0 and ends with -1. Tuple occupies lesser memory than the list. tuples take lesser time than list while working with billions of the data.

 # creating a tuple

tuple = (1,2,3,4,5)
# empty tuple
tuple = ()

Packing and Unpacking:  In the packing method, we place a value into a new tuple whereas in the unpacking method we extract those values into the variables.

x = (“Hello”, 20, “Excellent”)        # tuple packing

(hello, what, crude) = x           # tuple unpacking

All the methods of tuples are the same as that of the list. and let’s look at the comparison of the tuples.

# Example 1
a = (5,6)
b = (4,5)
if(a>b): 
   print("a is bigger")
print("b is bigger)

#Example 2

a = (5,6)
b = (6,7)
if(a>b): 
   print("a is bigger")
print("b is bigger)

OUTPUT:

a is bigger
b is bigger

Immutability: Tuples cannot be modified as they are immutable which means a given tuple cannot be changed.

a = (5,6)
a.append(15)
del a

OUTPUT:
Attribute error

To be honest, tuples are not used as often as lists in programming but are used when immutability is necessary. If in your program you are passing around an object and need to make sure it does not get changed, then a tuple becomes your solution. It provides a convenient source of data integrity.

Leave a Reply

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