Tuples in Python

Sakshi Dhameja  9 min read
21 Jul 2023
Beginner
669 Views

Introduction

If you are just getting started with a Python certification course, you've probably heard about tuples. Tuples allow for a more efficient and effective way to store data compared to other data structures like lists and dictionaries. Although they may seem complex at first, tuples are actually quite simple once you understand their purpose and how they work. In this article, we'll take a look at what makes tuples so special, tutorials on how to use them, as well as some clever ways in which you can employ them in your own programming projects. So if you're ready to get coding with Python's most infamous structure let us begin!

What are Tuples in Python? 

Python tuples are useful data structures found within the python language. They are an immutable sequence of objects, allowing for the storage and manipulation of data. A python tuple can contain a variety of elements, from strings to lists and dictionaries. Generally speaking, python tuples are created using parentheses and consist of separated elements found within those parentheses. For python users, understanding how to properly use python tuples can offer many advantages and help when manipulating complex data sets in python programming projects.

Example

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

How to access tuple elements in python

Accessing values in tuples is a simple but powerful way of handling data, allowing for faster manipulation and aggregation. Tuples offer the advantage of readability and ease of use, making it easy to mock up code tests or carry out quick calculations. Accessing the values within the tuple requires specifying their positions or indices within brackets, which could range from 0 to n-1. The same technique can be used to access multiple values if needed. Tuples should be considered if one needs a data structure that offers fast restriction as they are more efficient than pure lists. Accessing values in tuples is a necessary skill for anyone who works with searching and manipulating datasets.

Example

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

Output

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

Updating Tuples in Python 

Updating tuples in python is a great way to organize data efficiently. Updating tuples allows users to add, edit and delete elements in order to achieve the desired data sets. It is important to note that while tuple objects themselves are not mutable, they can be embedded with lists or dictionaries that can be changed. Further, it is necessary to understand that tuples are defined by parentheses and contain immutable objects such as strings, numbers, and other tuples inside them. By using the techniques of tuple packing, indexing, adding, and unpacking new elements, updating a tuple in python is easy yet powerful. Updating tuples provides an efficient way for developers to store their data in a more organized way.

Example

tup1 = (16, 44.26);
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;

Output

(16, 44.26, 'abc', 'xyz')

Delete Tuple Elements in Python

Deleting elements from a Python tuple can seem like a difficult process, but with the right understanding of list and tuple functionality, it is relatively simple. To delete elements in a Python tuple, one must first convert it to a list object. Once the object has been converted, elements can be freely added or removed from the list. After completing the desired changes, the list data structure can then be converted back into a tuple object. Delete Tuple Elements in Python is an elegant yet straightforward solution for managing powerful data sets.

Example

tup = ('mathematic', 'english', 1997, 2000);
print tup;
del tup;
print "After deleting tup : ";
print tup;

Output

('mathematic', 'english', 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 tuple operations in python

Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string. Tuple concatenation is mainly joining two tuples, which are often used to combine related pieces of information into a single unit of data. Tuple repetition is generally repeating the same tuple multiple times, which can be used to quickly construct large arrays of data. Tuple comparison operators let the user easily check for common elements or verify the sizes of the tuple.
Python Expression Results Description
len((1, 2, 3)) 3 Length
(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) True Membership
for x in (1, 2, 3): print x,1 2 3Iteration

Indexing, Slicing, and Matrixes in python

Working with data in python is made simple thanks to indexing, slicing, and matrices. By using index in python a certain element in an array with the index function in python, values can be accessed quickly and easily while looping through multiple records. Popular applications of indexing include web scraping and dealing with requests from databases. The slice operator in python can then be used to quickly copy or alter information within those records. Python also offers powerful opportunities for creating and manipulating matrices, which allow users to make computations that summarize large sets of data. Python matrix makes summarizing complex data simpler and provides users with greater insight into how their datasets are structured.
Python ExpressionResultsDescription
L[2]'SPAM!'Offsets start at zero
L[-2]'Spam'Negative: count from the right
L[1:]['Spam', 'SPAM!']Slicing fetches sections

Tuple built in functions in python

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

Summary
 In conclusion, learning the ins and outs of tuples in Python language can be demanding. But with proper Python Training, it can make life easier for developers by enabling them to store and access data efficiently. It is a useful feature that every programmer should become familiar with. Studying the usage and application of tuples in Python language is an essential tool for any python developer as understanding it can help them create more intricate programs quickly. With time and dedication, those interested in programming with Python language can gain a strong handle on the use of tuples. Take the initiative today and begin your exploration into the realm of tuples using Python language!

Share
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like Java, Python, C, C++ etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like JavaScript and Cloud.

Accept cookies & close this