What is Tuple in Python? Advantages & Features | DataTrained

Chandrakishor Gupta Avatar

Introduction

One of Python’s four built-in data types for storing collections is the tuple. Tuple in python, The items of tuples are ordered and immutable, in contrast to other data types. They have some built-in operations to work with them and are used to hold several elements in a single variable.

What is Tuple in Python?

What is Tuple in Python?

Python provides a variety of data structure collections, including dictionaries, sets, tuples, lists, and sets. However, these tuples resemble lists. The way tuples vary from lists, a frequently used data structure by developers, is typically unclear.

While lists and tuple in Python both consist of a collection of components of any data type, tuples are immutable, meaning that once they have been assigned, neither of their elements nor the tuple itself can be changed.

Features of Tuple in Python

The characteristics of a tuple in Python are as follows: 

  • Both heterogeneous and homogeneous data are stored in tuples.
  • In nature, tuples are immutable.
  • To navigate a tuple, use an index.
  • Lists and multiples are comparable. The order of the data is also preserved
  • Tuples are ordered

Syntax of Tuple in Python

Tuple Syntax

A tuple is initiated with the () symbol. 

Here’s an example of declaring a tuple in Python.

num_tuple = (1,2,3,4,5)

print(num_tuple)

alphabets_tuple = (‘a’,‘b’,‘c’,‘d’,‘e’)

print(alphabets_tuple)

A list can contain data of different data types. You can initiate it as follows – 

mixed_tuple = (‘a’, 1,‘b,’ 2,‘c,’ 3, ‘4’).

print(mixed_tuple)

You can create nested lists as well. A nested list is a list inside a list.

nested_tuple = (1,2,3,(4,5,6),7,8)

print(nested_tuple)

When to use Tuple in Python?

When to use Tuple in Python?

Tuples are immutable. As a result, they are mainly employed to store data that doesn’t change much. When you don’t want the data to change, any operation can save it in a tuple.

If you want the data in your collection to be read-only, never change, and always stay the same and constant, tuples are an excellent tool to utilize.

Tuple in Python can be utilized in dictionaries and sets, Python Enumerate, which demand that the items included therein be of an immutable type, as a result of this capability and the assurance that data is never modified.

Creating Python Tuples

Put all the items in a () parenthesis, separated by commas, to form a tuple in Python. A tuple can include both string and list data pieces in addition to heterogeneous data items. Using () operators, we will build a tuple.

values: tuple[int | str, …] = (1,2,4, “DATA”)

print(values)

Output – 

(1, 2, 4, ‘DATA’)

Here, in the above snipper we are considering a variable called values which holds a tuple that consists of either int or str, the ‘…’ means that the tuple will hold more than one int or string

Click here to know about: data science colleges in Pune

Accessing Values in Python Tuples

Accessing Values in Python Tuples

We use 0 to access the initial element of a tuple, 1 to access the next one, and so on because indexes begin at 0.

Method 1: Using a Positive Index

In Python, square brackets can be used to retrieve values from tuples.

var = (“DATA”, “for”, “DATA”)

print(“Value in Var[0] = “, var[0])

print(“Value in Var[1] = “, var[1])

print(“Value in Var[2] = “, var[2])

Output:

Value in Var[0] =  DATA

Value in Var[1] =  for

Value in Var[2] =  DATA

Method 2: Using Negative Index.

Here, we will utilize the -ve index within [instead of the positive index that we used in the ways above to retrieve the value in Python.

var = (“DATA”, “for”, “DATA”)

print(“Value in Var[-3] = “, var[-3])

print(“Value in Var[-2] = “, var[-2])

print(“Value in Var[-1] = “, var[-1])

Output:

Value in Var[-3] =  DATA

Value in Var[-2] =  for

Value in Var[-1] =  DATA

Slicing Python Tuples

# code to test slicing

tuple1 = (0 ,1, 2, 3)

print(tuple1[1:])

print(tuple1[::-1])

print(tuple1[2:4])

Output:

(1, 2, 3)

(3, 2, 1, 0)

(2, 3)

Also read: data science course fees in Mumbai

Updating Tuples

Updating Tuples

Due to their immutability, tuple in Python cannot be updated or have their element values changed. Mutable and Immutable in Python, The example that follows explains how you can combine pieces of already-existing tuples to generate new tuples−

#!/usr/bin/python

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;

Output

(12, 34.56, ‘abc’, ‘xyz’)

Python Tuple Methods

Tuple in Python do not support methods that add or remove items. There are only the following two options.

Several illustrations of Python tuple techniques:

my_tuple = (‘a’, ‘p’, ‘p’, ‘l’, ‘e’,)

print(my_tuple.count(‘p’))  # prints 2

print(my_tuple.index(‘l’))  # prints 3

Repetition Python Tuples

# Code to create a tuple with repetition

tuple3 = (‘python’,)*3

print(tuple3)

Output:

(‘python’, ‘python’, ‘python’)

Immutable Python Tuples

# code to test that tuples are immutable

tuple1 = (0, 1, 2, 3)

tuple1[0] = 4

print(tuple1)

Output:

Traceback (most recent call last):

  File “e0eaddff843a8695575daec34506f126.py”, line 3, in

    tuple1[0]=4

TypeError: ‘tuple’ object does not support item assignment

Finding Length of a Tuple

# Code for printing the length of a tuple

tuple2 = (‘python’, ‘DATA’)

print(len(tuple2))

Output:

2

Converting List to a Tuple

# Code for converting a list and a string into a tuple

list1 = [0, 1, 2]

print(tuple(list1))

print(tuple(‘python’)) # string ‘python’

Output:

(0, 1, 2)

(‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)

Deleting a Tuple

# Code for deleting a tuple

tuple3 = ( 0, 1)

del tuple3

print(tu
ple3)

Output:

(0, 1)

Advantages of Tuple in Python

  • Because they cannot be changed, tuples function as a write-protected collection. When we need to keep safe read-only data that cannot be altered throughout our code, the use of tuples can be advantageous.
  • Tuple in Python are a heterogeneous collection because it can hold data of many data kinds.
  • Tuple has a quicker iteration because it is a read-only collection.

Disadvantages of Tuple in Python

  • Tuple’s write protection is both a benefit and a drawback because it prevents us from using it to add or remove certain elements. Thus, it only has a few application cases.
  • less intelligible in terms of syntax because tuples can be generated with or without brackets depending on how many elements there are. But when there is only one element, employing brackets will not result in a tuple, hence a following comma is necessary. Tuple in Python, For some, this can make it difficult to interpret code.
  • A tuple is stored on the heap and adds overhead to the garbage collection because it is a class.

Conclusion

One of the data structures available in Python is the triple, which is immutable, ordered, has integer-based indexing, and supports storing duplicate data. Both parentheses and comma-separated items and no parentheses and comma-separated elements can be used to generate tuples. Python needs a trailing comma to recognize a string as a tuple if parenthesis is not used. It is not feasible to remove an element from a tuple. However, removing a tuple is.

Frequently Asked Questions

What is a tuple and list in Python?

Lists and tuples are two examples of data structures in Python that can hold one or more objects or values. Square brackets can be used to build lists, which are used to hold several elements in a single variable. Tuples, which can likewise store many items in a single variable and are specified using parenthesis, work similarly.

The only two differences between tuples and lists are that tuples utilize brackets rather than square brackets and that tuples’ items cannot be updated while lists’ elements can. Tuples are typically referred to as immutable, whereas lists are frequently referred to as changeable (meaning they can be modified).

Python Collections (Arrays)
A collection that is arranged and immutable is a tuple. allows for many members. A set is an unsorted, immutable, and unindexed collection.

The ‘*’ operator can be used when a tuple needs to be repeated ‘N’ times. An immutable data type is a tuple. As a result, values that have already been defined cannot be modified by accessing their index elements.

Transmit a tuple. Lists are mutable, thus you cannot clone a list with the = sign. A reference, not a copy, is made when you use the = symbol. Due to the immutability of tuples, the = sign should produce a copy rather than a reference when used.

We can use tuple slicing. I function the same way that strings and lists do. Basically, tuple slicing is used to get a variety of things.

Tagged in :

UNLOCK THE PATH TO SUCCESS

We will help you achieve your goal. Just fill in your details, and we'll reach out to provide guidance and support.