Learn About Python Tuples Function [With Examples]
Updated on Nov 19, 2024 | 6 min read | 7.5k views
Share:
For working professionals
For fresh graduates
More
Updated on Nov 19, 2024 | 6 min read | 7.5k views
Share:
Table of Contents
Tuples are sequences or a collection of objects separated by commas. They are similar to lists in many ways, except that the elements cannot be changed after they are created. And unlike lists, tuples in Python are immutable objects. Also, they use parentheses and not square brackets.
Creating a tuple is as simple as placing values separated by commas, sometimes between parentheses. Here are some examples:
As you can see, a tuple may have any number of elements, and they may be of different types – an integer, a list, a string, and so on. Using parentheses is optional, but considered a good practice to follow. Now, let us delve into the specifics.
If you are a beginner and interested to learn more about data science, check out our data science certification from top universities.
Read about: Operators in Python
An empty tuple comprises two parentheses with nothing inside, i.e., (). Here’s how you create it:
empty _tup = ()
print (empty_tup)
#Output
()
Now, let’s see how we can create non-empty tuples. Creating tuples without parentheses is called tuple packing.
tup=‘mouse’, ‘keyboard’
print(tup)
#Output
(‘mouse’, ‘keyboard’)
Alternatively, you can use parentheses for the same output.
tup= (‘mouse’, ‘keyboard’)
print(tup)
#Output
(‘mouse’, keyboard’)
For a single-element tuple, merely putting the one constituent within parentheses would not work. You will have to include a trailing comma to indicate that it is a tuple. Consider the following example.
tup=(50,)
To concatenate two tuples in python, you can write the following code:
my_tup=(0,1,2,3,4,5)
your_tup=(‘hello’, ‘bye’)
print(my_tup + your_tup)
#Output
(0,1,2,3,4,5, ‘hello’, ‘bye’)
Below is the code for creating nested tuples:
tup1=(0,1,2)
tup2=(‘python’, ‘learn’)
tup3=(tup1, tup2)
print(tup3)
#Output
((0,1,2),(‘python’,’learn’))
To create a tuple with repetition, follow the steps given below:
new_tup=(‘hi’,)*4
print(new_tup)
#Output
(‘hi’, ‘hi’, ‘hi’, ‘hi’)
On writing the above code without commas, you will get a string, hihihihi, as output for new_tup.
Read: Top 5 Python Modules
To access values in tuple, you use square brackets with the index. Take the code below to test slicing.
tuple=(0,1,2,3)
print(tuple[1:])
print(tuple[::-1])
print(tuple[2:4])
#Output
(1,2,3)
(3,2,1,0)
(2,3)
It is not possible to update or change the values of elements, but you can create new tuples by taking portions of existing tuples, as demonstrated in the example below.
tuple1=(‘ab’, ‘xy’)
tuple2=(13,14)
#action invalid for tuples
#tuple1[0]=50
#Creating a new tuple
tuple3=tuple1+tuple2
print tuple3
#Output
(‘ab’, ‘xy’, 13, 14)
Similarly, you cannot remove individual elements in tuples since they are immutable. However, you can put together another tuple to discard the undesired constituents. And you can remove the entire tuple by using the del statement explicitly.
tuple1=(‘January’, February’)
del tuple1
Also read: Python Developer Salary in India
upGrad’s Exclusive Data Science Webinar for you –
ODE Thought Leadership Presentation
There are various built-in tuple functions in python, such as len(), cmp(), max(), min(), and tuple(seq). Let us demonstrate their use one by one.
my_tuple = (‘upgrad’, ‘python’)
print(len(my_tuple))
#Output
2
tup1 = (‘upgrad’,’python’)
tup2 = (‘coder’, 1)
if (cmp(tup1, tup2) != 0):
# cmp() returns 0 if matched, 1 when not tup1
# is longer and -1 when tup1 is shorter
print(‘Not the same’)
else:
print(‘Same’)
#Output
Not the same
print (‘Maximum element in tuples 1,2: ‘ + str(max(tup1)) + ‘,’ + str(max(tup2)))
print (‘Minimum element in tuples 1,2: ‘ + str(min(tup1)) + ‘,’ + str(min(tup2)))
#Output
Maximum element in tuples 1,2: upgrad,coder
Minimum element in tuples 1,2: python,1
You will observe that the max() and min() checks are based on ASCII values. In case of two strings in a tuple, python checks the first different characters in the strings.
list1 = [0, 1, 2,3]
print(tuple(list1))
print(tuple(‘upgrad’)) # string ‘upgrad’
#Output
(0,1,2,3)
(‘u’, ‘p’, ‘g’, ‘r’, ‘a’, ‘d’)
Here, a single parameter, such as a list, string, set, dictionary key, is taken and converted into a tuple.
Now, let’s move on to creating tuples in a loop. You can follow the following python code to do it.
tuple=(’python’,)
n=3 #Number of time the loop runs
or i in range (int(n)):
tuple=(tuple,)
Print tuple
#Output
((‘python’,),)
(((‘python’,),),)
((((‘python’,),),),)
As you can see, there are different ways of creating a tuple and iterating over it.
Lists and tuples in Python are typically used in similar situations. But tuples are preferred over lists due to a variety of reasons. Some of them are listed below.
In this article, we understood all about tuples in Python, from what they are and how to create them to their different operations and benefits. This information will surely come handy as you move forward in your Python learning journey!
If you are reading this article, most likely you have ambitions towards becoming a Python developer. If you’re interested to learn python & want to get your hands dirty on various tools and libraries, check out Executive PG Programme in Data Science.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources