Home Blog Tuples in Python Programming
Tuples in Python Programming

Tuples in Python Programming

Tuples are immutable data structures that are used to store ordered collections of elements and allow duplicate values. They contain heterogeneous data types which means it is a mixture of integers, strings, floats, other tuples, lists and dictionaries. 

Tuples in python are often used for grouping related data together, and they can be useful for storing data that should not be changed during analysis.

Advantages

1. Immutable

Since tuples in python are immutable, their values cannot be changed after being created which makes it ideal for storing constant or fixed data. It also helps prevent bugs caused by making changes to data.

2. Memory Efficient

Python tuples consume less memory compared to lists as they are immutable and can be a good choice for storing large data sets where immutability is not an issue

3. Ordered Structure

Tuples preserve the order of their elements which allows us to do indexing and slicing.

Disadvantages

1) Tuples have a fixed size

We cannot add or remove elements once a tuple is created which makes it less flexible.

2) Limited functionality

Python tuples can be counterintuitive for newcomers who might expect list-like behaviour.

3) Tuples have methods

Count () and index () which makes it less versatile than lists which have methods for appending, removing, sorting and more.

How to create a Tuple?

Tuples are defined using round brackets () or by separating items with commas.

#creating a tuple
my_tuple=(‘harsh’,1,2,’ram’)
print (my_tuple)


One Element Tuple

When creating a single element tuple use a comma after writing the element.

tuple4=(‘harsh’,)
print (tuple4)
print (type(tuple4))


#NOT A TUPLE

Tuple1=(6)
print (tuple1)
print(type(tuple1))


In case you don’t include comma. 

When you use type function it will show as string, float, int, Boolean depending on the element unlike above

Tuple with variables elements

You can store variables in a tuple. 

#Tuple with variables
a,b,c=10,20,30
variables_tuple = (a,b,c)
print (variables_tuple)


Creating tuple Using tuple () constructor:

#using tuple constructor
tuple_=tuple(“Hello”)
print (tuple_)


Characteristics of Tuple

1. Immutable

Once you have created a tuple you cannot change the elements of a tuple directly however you can do it by converting it into a list and then converting back the list to tuple.

#immutable
my_tuple=(1,2,3,4,5,6,7)
my_tuple[0]=4
print (my_tuple)


#conversion of tuple into list and then again to tuple
print(my_tuple)
y=list(my_tuple)
y[3]='raj'
my_tuple=tuple(y)


2. Ordered

Once the order has been set you can access them using indexing and slicing 

Indexing starts at 0 that is the first element has index of 0.

#ordered
print (my_tuple)
print (my_tuple[2])


3. Allow Duplicates

Tuples can have duplicates elements you can add same element twice.

#allow duplicates
tuples1=(1,2,4,5,2,1,4)
print (tuples1)


Basic Built-in Functions for Tuple

1. len()

Length function will tell you the number of elements in the tuple.

#length of a tuple
my_tuple=(1,2,3,4,5,6,7)
print (len(my_tuple))


2. max()

This function is used to tell us about the maximum value present in tuple.

#maximum number in tuple
print (max(my_tuple))


3. min()

It returns the minimum value in the tuple. 

#minimum number in tuple
print (min(my_tuple))


4. sum()

It is a mathematical function that helps us to calculate the sum of numeric elements present in a tuple.

#sum of the tuple (1+2+3+4…)
my_tuple=(1,2,3,4,5,6,7)
print (sum(my_tuple))


For loop in tuple

The for loop is the easiest way to iterate through a tuple. It allows you to access each element one by one.

#for loop in tuple
for i in my_tuple:
    print (i)


While loop in tuple

You can also use a while loop to iterate through a tuple by manually managing the index.

#while loop in tuple
my_tuple = (10, 20, 30, 40)
index = 0

while index < len(my_tuple):
    print(my_tuple[index])
    index += 1


Looping through a Nested Tuple

If the tuple contains (nested tuples), you can use nested loops to access each element.

Here’s how:

#looping through a nested loop
nested_tuple = ((1, 2), (3, 4), (5, 6))

for inner_tuple in nested_tuple:
    for item in inner_tuple:
        print(item)


Tuple Comprehension

#Create a tuple of squares from the tuple elements
my_tuple=(1,2,3,4,5)
squares =tuple(x**2 for x in my_tuple)
print (squares)


The tuple () function converts the generated values into a tuple.

Tuple (expression for item in iterable if condition)

  • expression: What you want in each element of the tuple.
  • item: The variable representing each element in the iterable.
  • iterable: The source data (e.g., list, range, etc.).
  • if condition: Filters the elements of the tuple based on the condition.

Tuple Operations

  • Concatenation: Combine two tuples using the + operator.

t1 = (1, 2)

t2 = (3, 4)

print (t1 + t2)  

  • Repetition: we can Repeat elements using the * operator.

print (t1 * 3)

  • Membership Testing: Use in and not in to check if element exist or not

print (1 in t1)  

Other useful Operations

1. Indexing

By using indexing, you can access specific elements using their index values. Which starts from 0 and so on.

#indexing in tuple
print (my_tuple)
print (my_tuple[1])


2. Negative indexing 

Negative indexing allows you to access elements of a tuple starting from the end. Last element has an indexing of -1 and second last element have -2 so on.

#negative indexing in tuple
print (my_tuple)
print (my_tuple[-1])


3. Slicing

Extract a subset of elements using slicing.

#slicing in tuple
print (my_tuple)
print (my_tuple[1:4])


4. Negative Slicing  

In negative slicing it allows you to extract subsets of elements from a tuple, starting from the end.

#negative slicing in tuple
print (my_tuple)
print (my_tuple[-4:-1]


Common Uses:

  • Grouping of data:

It is Used to store related data together (e.g., coordinates (x, y) or user information (name, age, email)).

  • Function returns: 

used to return multiple values from a function.

  • Keys in dictionaries: 

Tuples can be used as keys in dictionaries because they are immutable.


Conclusion

In conclusion, Tuples in python are helpful for maintaining consistent data and especially when we want to work with immutable data.

Also Read: What are Sets in Python?

Get in touch wit​h us!

Protected by reCAPTCHA, Privacy Policy & Terms of Service apply.
Leave a Comment

Your email address will not be published.

Submit
Your comment is under review by our moderation team.