Tuples In Python

What tuples are, how to use them, and when to use them in python. The python programming language organizes and stores data in formats known as data structures. Each with unique behaviors, these data structures are lists, sets, tuples, and dictionaries.

In this article, we will talk about tuples. Before we dig in, however, let us define the other data structures.

  • Lists –A list holds several objects together in a sequence. The order of the items is significant, and you can access an element by its position, also called the index.
  • Set — A set also holds objects, only that the items are unordered and unindexed (meaning the positions or indices of the elements are not preserved). Also, sets drop duplicate items storing unique items.
  • Dictionary — A dictionary holds items in the form of a key-value pair. The values and associated keys are unordered and can appear in any position. Values can be accessed by their keys.

Tuples

A tuple, pronounced ‘tuh-pul,’ is a sequence of ordered items accessed by their index position. It is much like a list, except that the items in a tuple cannot be modified or changed once created.

Advantages of tuples

  • They take up less memory because tuples do not allow adding or removing elements, and python optimizes for this.
  • They are faster than lists. Tuples are simpler data structures by design and, therefore, quicker to create.
  • Tuples can hold objects of different data types, for example, string, boolean, and integers, in the same tuple.

Disadvantages of using tuples

  • Once created, the tuple contents cannot be changed.
  • Supports fewer functions compared to other data structures.

At the end of the article, we will explore some practical applications of tuples.

Become a Python Certified professional by learning this HKR Python Training!

Features of a tuple

  1. Immutable - The size of a tuple, or the number of elements, is fixed. Hence the memory allocated to tuples is explicitly set as it does not expect modification. 
  2. Heterogeneous - Tuples can store elements of different types (Heterogeneous) or the same data type (homogeneous).
  3. Indexed - Every element is held in its fixed position, and we can search for a value using its index.
Creating a tuple
There are three ways to create tuples.
  • Enclosing the elements inside a set of parenthesis (normal brackets), e.g. (‘a’,’b’,’c’)
  • Separating items with commas, e.g. ‘a’,’b’,’c’
  • Using the function tuple() and passing an iterable such as a list or a tuple, e.g., tuple([‘a’,’b’,’c’])

Create an empty tuple

You can either use empty parenthesis or the function tuple() without any arguments.

emp_tup = ()

Or

emp_tup = tuple()

If you print an empty tuple, it returns parenthesis.

print(emp_tup)
###
()

Creating a tuple with one element

  • Enclose inside parenthesis — To create a tuple with one element, always add a comma after the value inside the parenthesis. Without a comma, python assumes you are initializing a single value of a certain data type such as string, integer, etc.
#Correct way
tup1 = ('age',)
print(tup1)
###Output
('age',)
#Wrong way
tup2 = ('age')
print(tup2)
###Output
age

  • Using the tuple(iterable) function —  The function tuple() takes in an iterable such as a list, tuple, or set.
#pass in a list
tup1 = tuple(['age']) 
#tuple
tup2 = tuple(('age',))
#set
tup3 = tuple({'age'})
print(tup1, tup2, tup3)
###
('age',) ('age',) ('age',)

Python Training Certification

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Creating a tuple of several elements

  • Using parenthesis — Enclose the values with parenthesis.
my_tup = ('Lucy',24,'Student')
print(my_tup)
### ('Lucy', 24, 'Student')
print(type(my_tup)
### <class 'tuple'>

  • Without parenthesis — Provide the values separated by commas without enclosing them with parenthesis.
my_tup = 'Bill',45,'Banker'
print(my_tup)
### ('Bill', 45, 'Banker')
print(type(my_tup)
### <class 'tuple'>

  • Using tuple() function — pass the values as an iterable inside the tuple function.
my_tup = tuple(('Miriam',23,'Marketer'))
print(my_tup)
### ('Miriam', 23, 'Marketer')
print(type(my_tup)
### <class 'tuple'>

Creating a tuple from a list

As demonstrated earlier, we can create a tuple from list by using the tuple(list) function.

my_list = [6,7,8]
tup = tuple(my_list)
print(tup)
###(6, 7, 8)

If you pass a string to the tuple function, it will be split into its constituent characters because a string is essentially a list of characters.

tup = tuple('friend')
print(tup)
###('f', 'r', 'i', 'e', 'n', 'd')

Nesting tuples

This involves creation of a tuple of tuples.

tup1 = ('Levi',16)
tup2 = ('Leo', 15)
tup3 = (tup1, tup2)

Or

tup3 = tuple([tup1,tup2])
print(tup3)
###(('Levi', 16), ('Leo', 15))

Operations you can perform on a tuple

As previously mentioned, tuples cannot be modified after creation. Therefore, most operations involve investigating a tuple and its content.

Determine the size of a tuple

The len() function returns the size or the number of elements in the tuple.

my_tup = ('name','age','occupation')
print(len(my_tup))

Top 30 frequently asked Python Interview Questions!

Subscribe to our youtube channel to get new updates..!

Accessing elements in a tuple

  • Return all elements —  Display a tuple using the print() function.

my_tup = (24,'yes',True, 2020)
print(my_tup)
###(24,'yes',True, 2020)
 

You can also use a for-loop to print each element in its line.

for i in my_tup:
    print(i)
###
24
yes
True
2020
 

  • Return a single element —   Enclose the index in square brackets like tup[index]. Remember that the index positions begin at zero.


my_tup = (24,'yes',True, 2020)
#index 1 or second element
print(my_tup[1])
###yes
#index -1 or last element
print(my_tup[-1])
###2020
 

  • Return a section (Slicing the tuple) using tup[start:stop: step] — you can extract parts of a tuple using square brackets. Include the start index (included) and stop index(excluded), separated by a colon. An optional argument is a step which is the increment between each index. The result is a list.

tup1 = [20,22,24,26,28,30]
#return from index 1(included)
#to 4(excluded)
print( tup1[1:4] )
###[22, 24, 26]
#from the last index to the end
print( tup1[-1:] )
###[30]
#from the beginning to the end,
#increasing by 2
print( tup1[::2] )
###[20, 24, 28]
#from start to end,
#in reverse direction
print( tup1[::-1] )
###[30, 28, 26, 24, 22, 20]
Getting the Minimum, Maximum, and Sum of values
If the tuple contains only integers, we can get the elements’ min, max, and sum.
tup1 = (20,22,24,26,28,30)
print(max(tup1))
print(min(tup1))
print(sum(tup1))
###
30
20
150
For string values, we can get the min and max values. Note that an error is returned if the elements are of different data types.
tup2 = ('shela','zoe','anna')
print(max(tup2))
print(min(tup2))
###
zoe
anna
Deleting a tuple

Use the keyword del.
del my_tup



Applications of a tuple

  • To store data that you want to protect against change.
  • Tuples are also handy for storing data where the index of each item has a special meaning. For example, coordinate pairs such as (-1.2921, 36.8219) where index 0 is the latitude and 1 the longitude. Another example is storing the RGB colors for a GUI object such as (255,255,0), where the indices represent red, green, and blue colors.
  • Because they cannot be modified, tuples can be used as keys in dictionaries

If you want to Explore more about Python? then read our updated article - Python Tutorial.

Python Training Certification

Weekday / Weekend Batches

Conclusion

This article discussed tuples, one of python’s data structures that allows for immutable storage and access to heterogeneous data. Though not as popular, tuples are useful for storing constant data that should not be modified.

Related Articles

1. Python Functions

2. Golang Vs Python

3. Running Scripts In Python

Find our upcoming Python Training Certification Online Classes

  • Batch starts on 30th Sep 2022, Fast Track batch

  • Batch starts on 4th Oct 2022, Weekday batch

  • Batch starts on 8th Oct 2022, Weekend batch

Global Promotional Image
 

Categories

Request for more information

Amani
Amani
Research Analyst
As a content writer at HKR trainings, I deliver content on various technologies. I hold my graduation degree in Information technology. I am passionate about helping people understand technology-related content through my easily digestible content. My writings include Data Science, Machine Learning, Artificial Intelligence, Python, Salesforce, Servicenow and etc.