Tuesday, July 7, 2020

Python Tuples with examples

Hello guys! Welcome back to another section of my tutorial on Python. In this tutorial guide, we are going to be discussing about Python Tuples.

A Python tuple is a group of objects which are ordered and fixed. Tuples are sequences just like Python lists. The paramount differences between tuples and lists are, tuples can not be changed unlike lists and tuples uses parentheses, on the other hand lists makes use of square brackets. 

Creating a tuple in Python is a very easy process. It is as easy as putting in different comma separated values. Optionally, comma separated values can be put between parentheses. 


Below is a simple example -

tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

The empty tuple is written as two parentheses containing nothing -

tup1 = ();

In order to write a Python tuple which contains a single value in it, you have to  include a comma, even if only one value is included -

tup1 = (50,);

Just like string indices, tuple indices starts at 0, and they can be sliced, concatenated and so on.

Accessing Values in Tuples

To access values in a Python tuple, make use of the square brackets to slice along with the index or indices to obtain value available at the index.


Following below is a simple example which shows how to access values in a tuple -


tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];


Below is the output of the above example -

tup1[0]:  physics
tup2[1:5]:   [2, 3, 4, 5]

Updating Tuples

Python tuples are fixed which simply means you can't update and change the values of tuple elements, you are able to take portions of the existing tuples to create new tuples.


Below example explains how to use portions of existing tuples to create new tuples -


tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');

# Following action is not valid for tuples
# tup1[0] = 100;

# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;


Below is the output of the above example -

(12, 34.56, 'abc', 'xyz')

RECOMMENDED POST: Python Strings Tutorial

Deleting Tuple Elements

Removing individual tuples elements is not possible. Nothing is wrong with putting together another tuple with the undesired elements decarded.


To explicitly remove an entire tuple, just make use of the del statement. For example -


tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : ";
print tup;


This produces the following output. Note - that an exception is raised, this is because after del tup, tuple does not exist anymore -

('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
   File "test.py", line 9, in <module>
      print tup;
NameError: name 'tup' is not defined

Basic Tuples Operations

Python tuples respond to the + and * operators much like strings. These operators mean concatenation and repetition here too, except that the result is a new tuple, not a string.

Infact, tuples also responds to all the general sequence operations that we used on strings in the prior chapter -

Python ExpressionResultsDescription
len((1, 2, 3))3Length
(1, 2, 3) + (4, 5, 6)(1, 2, 3, 4, 5, 6)Concatenation
('Hi!',) * 4('Hi!', 'Hi!', 'Hi!', 'Hi!')Repetition
3 in (1, 2, 3)TrueMembership
for x in (1, 2, 3): print x,1 2 3Iteration


Indexing, Slicing, and Matrixes
Since tuples are sequences, indexing and slicing work the same way here as they do for strings. Assuming the following input -

L = ('spam', 'Spam', 'SPAM!')

Python ExpressionResultsDescription
L[2]'SPAM!'Offsets start at zero
L[-2]'Spam'Negative: count from the right
L[1:]['Spam', 'SPAM!']Slicing fetches sections

No Enclosing Delimiters
Any set of multiple objects, comma separated, written without identifying symbols, i.e. parentheses for tuples, brackets for lists, etc., will default to tuples as shown below -


print 'abc', -4.24e93, 18+6.6j, 'xyz';
x, y = 1, 2;
print "Value of x , y : ", x,y;

Below is the output of the above example -

abc -4.24e+93 (18+6.6j) xyz
Value of x , y : 1 2

RECOMMENDED POST: Python Pass Statement

Built-in Tuple Functions
Python includes the following tuple functions -

Sr.No.Function with Description
1cmp(tuple1, tuple2)
Compares elements of both tuples.
Gives the total length of the tuple.
Returns item from the tuple with max value.
Returns item from the tuple with min value.
Converts a list into tuple.

Alright guys! This is where we are rounding up for this tutorial post. In my next tutorial, we are going to be discussing about the Python Tulpe cmp() Method.

Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.


Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.