Python Tuples – A Step-By-Step Guide for Beginners

Updated on July 17, 2024

Article Outline

Tuples are the inbuilt data structure in the Python programming language. In Python, a tuple is similar to a list. It can store the values of different types of elements. In tuples, all values or elements are separated by commas. In Python, tuples are immutable data structures that cannot be modified after they are created.

What is a Python Tuple?

In Python, Tuple uses stored data in a single variable. Tuples are immutable, meaning they cannot be modified after creation. They are defined by enclosing elements within parenthesis ‘()’ separated by commas. Tuple has defined order. A tuple can store any type of data in a single variable. It can store boolean, string and integers.

 

Syntax of Tuple

 

myTuple = (1, 2, 3, 'hello', True)

 

The following program prints the simple tuple.

 

Program

 

tuple = ("Books","123", True) print(tuple)

 

Output

 

('Books', '123', True)
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Tuple Characteristics

There are some characteristics of tuples:

  • Ordered: Tuple data structures maintain the order of elements.
  • Immutable: Tuple data structures are immutable, It means we cannot change the elements of the tuple data structure.
  • Allow Duplicates: Tuple data structures can contain duplicate elements.

Python Tuple Types

Python programming language offers two primary types of tuples: named tuples and unnamed tuples.

  • Named Tuples: Named tuples can be created by class and assigning a name to the new class. Each element within a named tuple corresponds to field records. The following program demonstrates Named tuples.
  • Unnamed Tuples: Unnamed tuples are easy to create as compared to named tuples. Named tuples elements separated by command. They are storing unstructured data that does not necessitate naming. The following program demonstrates an unnamed tuple example.

Creating Python Tuples

There are various ways to create a tuple in the Python language. The following list is here:

  • Using round brackets
  • With one item
  • Tuple Constructor

 

Creating a tuple using the round brackets:  To create a tuple using the parenthesis () operators.

 

Program

 

var = ("Hello", "World", "Computer") print(var)

 

Output

 

('Hello', 'World', 'Computer')

 

Creating a tuple with one item:

 

Python 3.11 also provides another way to create a tuple. The following program demonstrates the code.

 

Program

values : tuple[int | str, ...] = (1,2,4,"Harry", "Potter", "Hermoine") print(values)

Output

 

(1, 2, 4, 'Harry', 'Potter', 'Hermoine')

 

Tuple Constructor in Python: The tuple constructor in the Python language allows us to create a tuple. The following program demonstrates the tuple constructor.

 

Program

 

tuple_constructor_example = tuple(("dsa", "development", "deep learning")) print(tuple_constructor_example)

 

Output

 

('dsa', 'development', 'deep learning')

The following operations are performed in tuples in Python language.

 

  • Concatenation
  • Nesting
  • Repetition
  • Slicing
  • Deleting
  • Finding the Length
  • Multiple Data Type with tuples
  • Conversion of the list to tuples
  • Tuples in a Loop

Tuple Membership Test

In Python, we can also check whether the substring is in string or using the in operator. If the string is available in Python, it will return true; otherwise, it will return false. The following program demonstrates the tuple membership test.

 

Program

 

tuple_ = ("Hello", "Computer", "Wordholic", "Scientist", "Torture", "Multiple Disorder") # In operator print('Hello' in tuple_) print('Items' in tuple_) # Not in operator print('Immutable' not in tuple_) print('Items' not in tuple_)

 

Output

 

True False True True

How to Access Tuples?

In Python, tuples are accessed similarly to lists, but they are immutable; this means we cannot change their elements once they are created. Let’s see how we can access the Tuples.

 

Accessing by Index: We can access elements in a tuple using the square brackets.’[]’ and pass the index. Python uses zero-based indexing. It means the first element is 0.

 

Program

 

myTuple = (1, 2, 3, 4, 5) print(my_tuple[0]) print(my_tuple[2])

 

Output

 

1 3

 

Negative Indexing: We can also access the element from the end of the tuple using the negative indices.

 

Program

 

myTuple = (1, 2, 3, 4, 5) print(my_tuple[0]) print(my_tuple[-2])

 

Output

1 4

 

Slicing: You can also use slicing with tuples. In slicing, you can specify a range of indexes by specifying where to start and where to end the range.

 

The following program demonstrates the use of the slicing technique.

 

Program

 

myTuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) subset_tuple = my_tuple[2:7] print(subset_tuple) subset_with_step = my_tuple[1:9:2]  # Start from index 1, end at print(subset_with_step) subset_from_beginning = my_tuple[:5] print(subset_from_beginning) subset_to_end = my_tuple[5:] print(subset_to_end) subset_negative_indices = my_tuple[-5:-2] print(subset_negative_indices)

 

Output

 

(3, 4, 5, 6, 7) (2, 4, 6, 8) (1, 2, 3, 4, 5) (6, 7, 8, 9, 10) (6, 7, 8)

How to Update Tuples?

Python tuple is unchangeable. This means we cannot change the original tuple. If you attempt to directly modify a tuple, you’ll encounter an error. However, you can achieve a similar effect by creating a new tuple or converting a tuple into a list and then converting the list once again into a tuple.

 

Concatenation: We can modify a tuple using the concatenation of two tuples to create a new tuple.

 

Program

 

tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) updated_tuple = tuple1 + tuple2 print(updated_tuple)

 

Output

(1, 2, 3, 4, 5, 6)

 

Reassignment: You can assign a tuple variable to a new tuple that contests the updated values.

 

The following program demonstrates the reassignment example:

 

Program

 

my_tuple = (1, 2, 3) my_tuple = my_tuple + (4, 5, 6) print(my_tuple)

 

Output

 

(1, 2, 3, 4, 5, 6)

 

Convert tuple into a List: We can also convert the tuple and add the value in the list back to the convert-in tuple to modify it.

 

The following program demonstrates the convert tuple into a list:

 

Program

 

myTuple = (1, 2, 3) myList = list(my_tuple) myList[1] = 5 myTuple = tuple(my_list) print(my_tuple)

 

Output

(1, 5, 3)

 

Also read: Pandas in Python

How to Unpack Tuples?

In Python, unpacking is a convenient way to assign value to individual variables. It can be done by a single line of code. The following program demonstrates “how we can unpack the tuple”.

 

Program

 

# Define a tuple myTuple = (1, 2, 3) # Unpack the tuple into individual variables a, b, c = myTuple # Print the variables print(a) print(b) print(c)

 

Output

 

1 2 3

 

Using Asterisk: If the number of variables is less than the number of values, we can use the * to the variable name. It assigns the rest of the values in a single variable.

 

The following program demonstrates the using the asterisk:

 

Program

 

myTuple = (1, 2, 3, 4, 5) first, *rest = my_tuple print(first) print(rest)

 

Output

1 [2, 3, 4, 5]

 

Also read: List in Python

How to Use a Loop with Tuples?

We can also use loops with tuples in the Python programming language. It iterates over the elements of the tuple. There are many ways to do this using for-loop.

 

Using for loop: The following program demonstrates the for loop with tuples.

 

Program

 

my_tuple = (1, 2, 3, 4, 5) # Iterate over the tuple using a for-loop for item in my_tuple: print(item)

 

Output

 

1 2 3 4 5

 

Using a while loop: The following program demonstrates the while loop for tuples.

 

Program

 

myTuple = (1, 2, 3, 4, 5) index = 0 # Using a while loop to iterate over the tuple while index < len(my_tuple): print(my_tuple[index]) index += 1

 

Output

 

1 2 3 4 5

How to Join Two Tuples?

We can also join two tuples using the ‘+’ operators to concatenate them. It will create a new tuple that contains both elements from both tuples.

 

The following program demonstrates the joining of two tuples:

 

Program

tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) # Joining two tuples using the + operator joined_tuple = tuple1 + tuple2 print(joined_tuple)

 

Output

(1, 2, 3, 4, 5, 6)

We can also use the tuple constructor to join two tuples. The following program uses the tuple constructor.

 

Program

 

tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) # Joining two tuples using the tuple() constructor joined_tuple = tuple(tuple1 + tuple2) print(joined_tuple)

 

Output

 

(1, 2, 3, 4, 5, 6)

Deleting a Tuple in Python

In this section, we will delete the tuple using the del keyword. The output will form an error because you have already deleted the tuple. It will give the NameError.

 

Remember: We cannot delete the individual element from the tuple. But we can delete the whole tuple using the del keyword.

 

Program

 

# Code for deleting a tuple tuple3 = ( 0, 1) print(tuple3) del tuple3 print(tuple3)

 

Output

 

(0, 1) ERROR! Traceback (most recent call last): File "<main.py>", line 5, in <module> NameError: name 'tuple3' is not defined

Finding the Length of a Python Tuple

We can find the length of a tuple using the Python len() function and pass the tuple as the parameter.

 

Program

 

# Code for printing the length of a tuple tuple2 = ('python', 'computer','wrong', 'song') print(len(tuple2))

 

Output

 

4

Multiple Data Types With Tuplecture

In Python, Tuples are heterogeneous data structures. This means they support elements with multiple data types. The following program demonstrates the use of multiple tuples in a single tuple.

 

Program

 

# tuple with different data types tuple_types = ("Workaholic problem",True,23) print(tuple_types)

 

Output

 

('Workaholic problem', True, 23)

Converting a List to a Tuple

We can convert the list into a tuple using the tuple constructor. The following program demonstrates the list to a tuple.

 

Program

 

# Code for converting a list and a string into a tuple list1 = [0, 1, 2] print(tuple(list1)) # string 'python' print(tuple('Harry Potter’))

 

Output

 

(0, 1, 2) ('H', 'a', 'r', 'r', 'y', ' ', 'P', 'o', 't', 't', 'e', 'r')

Nesting of Python Tuples

We can also nest tuples in the Python language. Nesting is the process of placing a tuple inside another tuple. Let’s look at this tuple for clarity.

 

Example

tuple = (12, 23, 36, 20, 51, 40, (200, 240, 100))

The following program demonstrates the Nesting tuple example.

Program

tuple=(12,55,"harry",True,(200,300,400,7000)) print(tuple)

Output

(12, 55, 'harry', True, (200, 300, 400, 7000))

Repetition Python Tuples

We can also create a tuple of multiple elements from a single element in that tuple. The following program demonstrates the repetition of a Python tuple.

 

Program

 

tuple3 = ('python',)*10 print(tuple3)

 

Output

 

('python', 'python', 'python', 'python', 'python', 'python', 'python', 'python', 'python', 'python')

Difference Between List and Tuples

The following table shows the difference between a list and a tuple.

 

Python Lists Python Tuples
List are mutable data structures in Python Tuples are immutable data structure
In list iteration is time-consuming In tuples, iterations are comparatively faster than list
Inserting and deleting items is easier with a list Accessing the elements is best accomplished with tuple data type
List consumers with more memory in the computer system. Tuples consume less memory than list
In the list, unexpected changes occur more as compared to a tuple Because lists are mutable In a tuple, changes and more errors don’ n’t usually occur because of immutability

Built-in Methods

Built-in-Method Description
index() Find in the tuple and return the index of the given value if the value is available
count() This method returns the frequency of occurrence of species value.

Conclusion

In this article, we learned about tuples in Python and saw that they are immutable data structures. After defining a tuple, we cannot change its original state. A tuple stores heterogeneous elements. It can store different data types, including number, strings list, and other tuples. We also learned various approaches to access the tuple and modify the existing tuple. Overall, tuples provide a lightweight and efficient way to store and work immutable sequences of data in Python. If you want to learn more about the Python language, consider pursuing the Accelerator Program in Business Analytics and Data Science.

 

FAQs
A tuple is an ordered and immutable collection of elements. Tuple enclosed within parenthesis ‘()’. It can contain elements of different data types, separated by commas.
Tuples can be created by enclosing within parentheses ‘()’, separated by command, for example ‘myTuple=(1,2,3)’.
We can iterate over a tuple using a ‘for’ loop and ‘while’ loop or other iterable methods like ‘enumerate()
Yes, we can concatenate two tuples using the ‘+’ operator or the ‘tuple()’ constructor.
Indexing can access a tuple. In Python, indexing starts at 0. ‘Mytuple[0]’ will access the first element.

Updated on July 17, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved