×

Tuple in Python

Tuples

Tuples are the same as the list but as we know that lists are mutable means we can change the data from it. In the tuple we cannot change the data from the tuple once we assign it.

It is also called the collection of the ordered elements which are separated by commas and also they are immutable.

Example:

Tuple_A = ("Python", "Java", "c#", "C++")  
Tuple_B = (3, 2, 1, 5, 6)  
Tuple_C = "Python", "Java", "c#", "C++"

Creating the Tuples  

If we want to create the tuple then we need to enter all the data inside the parentheses ( ), data must be separated by commas. The parentheses are optional without parentheses we can create the tuple. But using parentheses is good practice. Tuple can store any type of data, that data can be integer, float, list, or string.

Program:

#Types of tuples


# Empty tuple
tuple_z = ()
print(tuple_z)


# Tuple contaning integers
tuple_z = (12, 23, 35)
print(tuple_z)


# tuple contains  different  datatypes
tuple_z = (11, "Hie", 32.4)
print(tuple_z)


# nested tuple
tuple_z = ("Monitor", [18, 34, 46], (1, 2, 3))
print(tuple_z)

Output:

()
(12, 23, 35)
(11, 'Hie', 32.4)
('Monitor', [18, 34, 46], (1, 2, 3))

Explanation:

  • Firstly, we created the empty tuple, which means the tuple which not contain any data in it, we printed the empty tuple.
  • In the second tuple, we have inserted some integers in that tuple. Then we printed that tuple.
  • Then in the third tuple, we have inserted mixed data means that the tuple contains the integer, string, and float values in one variable. Then we have printed the tuple.
  • Then we have the nested tuple which containsa list in that tuple also another tuple in it it is called a nested tuple. Then, we printed the data.

Creating the Tuples with one element

In python creating a tuple having only one element is quite tricky. if we write one element in the parentheses that is not enough. For that, we need to add a comma after the first element.

#String
A = ("hi") 
#tuple
B = ("hi",)

With the help of type(), we can check which type of data it is.

Program:

A = ("hi")
print(type(A))  


# tuple with one element
B = ("hi",)
print(type(B)) 


# Without Parentheses
C = "hi",
print(type(C))  

Output:

<class 'str'>
<class 'tuple'>
<class 'tuple'>

Explanation:

  • In variable A we have assigned the new tuple in that we have inserted the “hi”.  But we have forgotten to add the comma in this now it will consider as a string. We have printed the type of the variable also.
  • In variable B we have added the comma in the tuple now it will consider it as a single tuple.
  • In variable C we have created a single tuple without parentheses.

Accessing tuple element

To access the elements from the tuple we will use the index. Like a list every element in the tuple is represented by the index number, the first element starts with the index 0.

Indexing:

With the help of the index operator, we can access the data/item from the tuple. The indexing of the tuple starts with 0. This means the first element is present at the 0th index. If any tuple has 8 elements then the indexing will be from 0 to 7. If you try to access the element which is outside of the index range then it will raise the IndexError.

The index should be an integer if you use another data type then it will raise the error which is TypeError.

Program:

# accessing elements using indexing
A = ("N", "E", "W", "S", "T", "A", "T", "E", "I", "N")


print(A[0])  
print(A[5])

Output:

N
A

Explanation:

Here we have the tuple which is A. Then with the help of the index function, we printed the data which is present in the first location as well as the data present in the sixth location.

Negative Indexing:

Python also supports negative indexing. The -1 in the reverse-indexing tells that you are at last elements.

Program:

# accessing elements using negative-indexing
A = ("N", "E", "W", "S", "T", "A", "T", "E", "I", "N")
print(A[-1])  
print(A[-5])  

Output:

N
A

Explanation:

  • Here, we have the tuple which is A.
  • Then with the help of reverse indexing, we have access to the elements from the tuple.
  • We have accessed the last element with reverse indexing
  • Then we also accessed the 6th element using reverse indexing.

Slicing:

Python also supports slicing. In the slicing, we will select the particular sequence of items using the slice operator.

In the slicing operator, we need to specify the starting index and ending index of the object.

In other words, we can say that slicing is used to cut a particular tuple as per our needs.

Program:

# tuple 
A = ('A', 'Z', 'W', 'R', 'D', 'F', 'T', 'U', 'V')


# elements 3rd to 5th index
print(A[2:5]) 


# elements from start-index to 3rd index
print(A[:-6]) 


# elements 5th to end
print(A[5:]) 


# elements start to end of the tuple
print(A[:])

Output:

('W', 'R', 'D')
('A', 'Z', 'W')
('F', 'T', 'U', 'V')
('A', 'Z', 'W', 'R', 'D', 'F', 'T', 'U', 'V')

Explanation:

  • Here, we have the tuple A. which contains the data in it.
  • In the first operation we have done with the slicing function we printed the data from the 3rd to 5th index.
  • Then, we have done another operation in which we printed data from the first index to the 3rd index.
  • Then, in the next operation, we printed data from the 5th index till the end.

Then, in the last operation, we printed data from starting index to the end index.

Methods in Tuple

There are two methods add items and remove items that are not available in the tuple.

Count:

In the count function, it will work to count the repetition of the particular element in the tuple.

Program:

# tuple 
Z = ('A', 'P', 'Z', 'R', 'A', 'T', 'F', 'U', 'A')


#counting repeated elements
print("Count -: ",Z.count('A'))

Output:

Count -:  3

Explanation:

In this, we have the tuple which is z. Then, with the help of the count function, we have printed how many times element ‘A’ is repeated in the tuple Z.

Index

  • The index function is used to get the index of the particular elements.
  • If you want to know the index of a particular element then you can use the index function.

Program:

# tuple 
Z = ('A', 'P', 'Z', 'R', 'A', 'T', 'F', 'U', 'A')
#Getting index of element
print("Index -: ",Z.index('T'))

Output:

Index -:  5

Explanation:

Here we have the tuple Z. Then, we have to use the index function so that it will return the index of the element ‘T’.

Traversing Tuple:

In this, we can traverse the tuple with the help of for loop.

Program:

Z = ("Yashraj", "Rohit", "Sumit", "Yogesh", "Akash")


# Traversing through the tuple
for Z in Z:
    print(Z)

Output:

Yashraj
Rohit
Submit
Yogesh
Akash

Explanation:

Here we have the tuple Z which contains the random names. Then, we have to use the for loop with the help of this loop we will traverse the tuple. We have printed the data which is in the tuple.

Checking Element in Tuple

If we want to check that a specific item is present in the tuple then you can use in keyword for the checking.

Program:

Z = ("Yashraj", "Rohit", "Sumit", "Yogesh", "Akash")
print('Yashraj' in Z)   
print('Mohit' in Z)

Output:

True
False

Explanation:

  • Here, we have the tuple Z which contains the random names.
  • Then, we have to use the print function and in that print function, we have to use the in keyword.
  • Now, those names which are present in the tuple Z and also in the in a keyword then it will return the True.
  • Those who are not present will return false for that condition.

Advantages of Tuple

  • Tuples are similar to the list so we use both in similar situations.
  • We use the tuple when we have different data types. But when we use the list at that time we have similar data type elements.
  • Tuples are unchangeable (immutable) so traversing through tuples becomes easy and faster as compared to the list.
  • A tuple contains the unchangeable (immutable) elements so that we can use that element as the key for the dictionary, but in the list, it is not possible.
  • Tuples are unchangeable (immutable) so no any other can change the data in them. Tuples give the guarantee that data in it remains safe.

Disadvantages of Tuple

  • In a tuple, if we want to add an element we cannot add the new element to the existing tuple.
  • It is difficult to sort the tuple.
  • We cannot remove the items/elements from the tuple.
  • If we want to replace the element from the tuple then it is not possible in the tuple.

Related Topics

Python String

Python String Python string is considered as the most popular data type present in Python language. In Python, string data type is the collection of characters, letters, white spaces etc. written...

31 minutes read.

Python bytearray()

Python bytearray() Class The bytearray() class is used to return a bytearray object which is an array of the specified bytes. It gives a mutable sequence of integers in the range 0...

1 minute read.

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

How to reverse a string in Python

In Python language, we have a few ways to reverse a string. In this article, let us discuss these ways and understand the suitability of these ways in different scenarios...

5 minutes read.

Application to Search Installed Application using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Paramiko Python Example

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Sublime Python

SUBLIME: A compact, cross-platform code editor called Sublime Text 3 (ST3) is well-known for its quickness, usability, and robust community support. Although it's a fantastic editor out of the box, its...

6 minutes read.

Reverse a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Find key from value in dictionary python

Python: Python programming language is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a...

5 minutes read.

Python getattr() function

Python getattr() function The getattr() function in Python returns the value of the named attribute for the given object. Syntax getattr(object, name[, default]) Parameter object: It is a required parameter which represents an object. name: This parameter represents the...

1 minute read.

Sort a dataframe based on a column in Python

Sorting the dataframe based on a column requires pandas which is An open-source library called Python Pandas is described as offering high-performance data processing in Python. For both professionals and...

4 minutes read.

Python String startswith() method

Python String startswith() method The string.startswith() method in Python returns a boolean value ‘True’ if the given string starts with the prefix, otherwise it returns False. Syntax startswith(prefix[, start[, end]]) Parameter prefix: This parameter signifies the value to check. start(optional):...

1 minute read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Python Trigonometric Functions

Before jumping right into the functions and how to use them we need to know what do trigonometric functions mean and how many functions does python has. What are Trigonometric functions? Trigonometric...

3 minutes read.

Python String find() method

Python String find() method The string.find() method in Python finds the first occurrence of the specified value and returns the lowest index in the string if the substring sub is found else it...

2 minutes read.

Python Matrix Operations

Python Matrix In this section of the Python tutorial, we will look at the introduction of the matrix in Python programming. We will perform many operations on the Python matrix using...

21 minutes read.

How to append an Array in Python

A group of objects kept at adjacent memory regions is known as an array. It is a container with a set capacity for a certain number of things, all of...

7 minutes read.

Python hash() function

Python hash() function The hash() function in Python returns the hash value of the object (if it has one).  Syntax hash(object) Parameter obj : This parameter represents the object which we need to convert into hash. Return This...

1 minute read.

Problem-solving with algorithm and data structures using Python

What is problem-solving? There is no universal method for solving problems. It's frequently a special process that balances your immediate and long-term goals with your available resources. However, several models emphasise...

3 minutes read.

One Liner If-Else Statements in Python

Before learning one liner if else Python, let us first know what Python is. Python is a broadly helpful, object-oriented and dependable language having a large number of utilizations from...

4 minutes read.