Browse Tutorials
Tuples in Python with Examples - A Beginner Guide

Tuples in Python with Examples - A Beginner Guide

29 Mar 2024
Beginner
1.5K Views
12 min read
Learn via Video Course & by Doing Hands-on Labs

Python Programming For Beginners Free Course

Tuples in Python with Examples: An Overview

If you are just getting started with a Python certification course, you've probably heard about tuples. In this Python Tutorial, 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 use them in your programming projects. So if you're ready to get coding with Python's most infamous structure let us begin!

What are Tuples in Python?

Tuples are ordered collections of elements, similar to Python lists, but they are immutable. This implies that once a tuple has been created, it cannot be altered.Parentheses() are used to define tuples, while commas are used to separate the elements. They help store data that should not be modified, such as constants or sets of related data.

Creating Tuples in Python

In Python, there are multiple methods for creating a tuple. They are listed in the following order:

  1. Making use of round brackets
  2. With just one item
  3. Tuple Constructor

Read More - 50 Python Interview Questions

1. Making use of round brackets

Python uses round brackets () to define tuples. Commas are used to separate the elements inside the brackets.

Example of Creating Tuple in Python using Round Brackets

        scholarhat_articles = ("C", "C++", "Python", "Java")
print(scholarhat_articles)
The tuple scholarhat_articles is defined in this code in the Python Compiler, which is then printed. Four strings ("C", "C++", "Python", and "Java") that relate to articles about programming languages are stored in the tuple.

Output

('C', 'C++', 'Python', 'Java')

2. With just one item

In Python, a comma must be added after the element to create a tuple with just that one element. It will be understood as a string type otherwise.

Example of Creating Tuple in Python using just one item

        favorite_color = ("blue",)
print(f"My favorite color is: {favorite_color[0]}")

With a comma, this code generates a tuple called favorite_color that has the sole element "blue" in it. Prints a description along with the element (which is "blue") at index 0.

Output

My favorite color is: blue

Read More - Python Developer Salary in India

3. Tuple Constructor

You can construct tuple objects in Python from many data structures by using the tuple constructor. It is essentially an inbuilt function in python that accepts an iterable as input and outputs a tuple with all its elements.

Example of Creating Tuple in Python using Tuple Constructor

        my_list = ["apple", "banana", "cherry"]
my_tuple = tuple(my_list)
print(f"List: {my_list}")
print(f"Tuple: {my_tuple}")
This code in the Python Online Editor generates a list of fruits with the names "apple," "banana," and "cherry" that it calls my_list.Using the tuple() constructor creates a tuple named my_tuple from the list. Uses f-strings to print the list and the tuple along with relevant messages.

Output

List: ['apple', 'banana', 'cherry']
Tuple: ('apple', 'banana', 'cherry')

How to Access Tuple Elements in Python

In Python, tuples are immutable lists of elements enclosed in parentheses. Different techniques can be used to access individual items within a tuple:
  • Use the index in square brackets: By utilizing their index, you can access particular elements (starting from 0).
  • Use a negative index: Access elements starting at the end (last element, -1, for example).
  • Use slicing: Colon (:) can be used to access various elements.
  • Use unpacking: Extract several elements into different variables.

Example of Accessing Tuple Elements in Python

        fruits = ("apple", "banana", "cherry")
# Access the second element (banana)
second_fruit = fruits[1]
print(second_fruit) # Output: banana
# Access the last element (cherry)
last_fruit = fruits[-1]
print(last_fruit) 

After defining a tuple of fruits, this code uses positive indexing to access the second element ("banana") and negative indexing to get the last element ("cherry").

Output

banana
cherry

Updating Tuples in Python

You can update an element by slicing the original tuple and substituting the new value for the desired element.Tuple concatenation is another tool you can use to join the modified and original items together.

Example of Updating Tuples in Python

        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)

This code creates a new tuple called tup3 by combining two defined tuples, tup1 and tup2. It shows that while merging tuples is okay, changing a tuple is restricted.

Output

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

Delete Tuple Elements in Python

The process of deleting the complete tuple object from memory is referred to as "delete tuple" in Python. This is not the same as removing specific tuple elements, which cannot be done because of their immutability.

Example of Deleting Tuple Elements in Python Editor

        original_tuple = ("apple", "banana", "orange", "grapefruit")
deleted_tuple = original_tuple[1:]
print("Original tuple:", original_tuple)
print("Deleted tuple:", deleted_tuple)

Four fruits make up the "original_tuple" that this code defines. The first member ("apple") is then removed using slicing to generate a new tuple called "deleted_tuple" (original_tuple[1:]). Lastly, it prints the changed and original tuples.

Output

Original tuple: ('apple', 'banana', 'orange', 'grapefruit')
Deleted tuple: ('banana', 'orange', 'grapefruit')

Basic tuple operations in Python

Tuples in Python are ordered collections of immutable objects, which means that once the tuple is created, its individual parts cannot be changed. On the other hand, you can manipulate and explore their contents using a variety of methods. These are a few fundamental tuple operations:
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

  • The process of using an index to retrieve a particular element from a sequence (list, string, tuple, or array) is known as indexing.
  • Extracting a subsequence from a sequence is referred to as "slicing." Within square brackets, you give the beginning index and the ending index (inclusive).
  • A rectangular array of data is called a matrix. Every element has a unique index for both rows and columns.
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.

Different Operations Related to Tuples

  • Concatenation: The joining of two or more lists to form a new list.
  • Nesting: Nesting is the process of putting one list inside another.
  • Repetition: Making many copies of a list is an example of repetition.
  • Slicing: Slicing is the process of extracting a part of a list.
  • Deleting: The act of removing an item from a list.
  • Determining the length: Counting the number of elements in a list.
  • Multiple Data Types Using Tuples: Storing different data types in a tuple.
  • Converting a list to a tuple: Making a tuple from a list.
  • Tuples in a Loop: Iterating over the items in a tuple.
Summary
Proper Python Training, can make life easier for developers by enabling them to store and access data efficiently. 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. Take the initiative today and begin your exploration into the realm of tuples using Python language!

FAQs

Q1. What are tuples?

Tuples are ordered collections of immutable objects that, like lists, cannot be updated after they are created.

Q2. How to access tuple elements?

Square brackets (tup1[1]) contain the element's index, which starts at 0. For end elements, tup2[-1] has a negative index.

Q3. How to update tuples?

Since tuples are immutable, it is not possible to directly edit their elements. To accomplish the desired change, you can instead use slice operations or construct a new tuple.

Q4. How to delete tuples?

A tuple can be completely removed from memory by deleting it. Del tup1 is the del keyword used to accomplish this.

Share Article
Batches Schedule
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js 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 Core Java, Python and Cloud.

Accept cookies & close this