Tuples in Python with Examples - A Beginner Guide

Tuples in Python with Examples - A Beginner Guide

03 Jul 2025
Beginner
11.4K Views
29 min read
Learn with an interactive course and practical hands-on labs

Free Python Programming Course For Beginners

Python tuples are ordered, immutable collections of items. Tuples are similar to lists in Python; the only difference is that tuples are immutable. Once a tuple is created, its values cannot be changed or updated, ensuring data integrity. Real use cases of tuples are storing bank account numbers, user IDs, color codes, etc.

In this Python Tutorial, we are going to learn what a Python tuple with examples is, show you how to create a tuple in Python, and perform basic tuple operations.

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.
  • There are various concepts related to tables, such as tuple datatypes, methods, and operations. Let's see one by one

tuples in python

Example:


my_tuple=(1,2,3,4,5)
my_tuple1=(1,’ScholarHat’)

print(my_tuple) 
print(my_tuple1)

1. Python Tuple Data Type

The most basic sequence that Python has to offer is most likely the built-in tuple data type. Tuples have a fixed number of elements they may hold and are immutable. Tuples can be used to represent a variety of sequences of values, such as records in a database table (name, age, and job), RGB colors (blue, green, and red), and Cartesian coordinates (x, y).
The components in the underlying tuple are fixed, and the number of elements is fixed in all these use cases. These two qualities may be useful in a variety of circumstances. Think about the RGB color example:
>>> blue= (0, 0, 255)

After blue has been defined, there is no need to modify or add any further elements. Why? Your variable name will be misleading if you alter the value of even one component, as you will no longer have a pure blue color. Your color won't be an RGB color if you add a new component. Therefore, tuples are ideal for representing this kind of data.

2. Characteristics of Tuple

  • Ordered: The elements are grouped sequentially based on the order in which they were inserted.
  • Lightweight: In comparison to other sequences like lists, they need very little memory.
  • Zero-based indexable: You can retrieve their elements using integer indices that begin at zero.
  • Immutable: They are resistant to alterations or in-place mutations to the elements they contain. They don't encourage operations to expand or contract.
  • Heterogeneous: They are capable of holding changeable objects as well as objects with a variety of data types and domains.
  • Nestable: You can have tuples of tuples since they can hold other tuples.
  • Iterable: You can work with each of their elements by performing operations on them using a loop or comprehension, as they allow for iteration.
  • Sliceable: You can extract a number of elements from a tuple because they allow slicing operations.
  • Combinable: They can be used to combine two or more tuples using concatenation operators to create a new tuple because they support concatenation operations.
  • Hashable: When every tuple item in a dictionary is unchangeable, they can function as keys.

3. Tuple Objects

Sequences of objects are called tuples. Because a single tuple can contain or gather an infinite number of other objects, they are frequently referred to as containers or collections.
Tuples in Python maintain their elements in the order in which they were originally inserted since they are ordered:
>>> record = ("Sourav", 25, "SEO Manager")

>>> record
('Sourav', 25, 'SEO Manager')

This tuple's elements are objects of various data types that each represent a record of information from a database table. Accessing the tuple object will reveal that the data pieces maintain their original sequence of insertion. Throughout the tuple's existence, this order doesn't change.Within a tuple, you can retrieve specific objects using their index or position. Each of these indices begins at zero:

>>> record[0]
'Sourav'
>>> record[1]
25
>>> record[2]
'SEO Manager'

How to Create Tuples in Python?

In Python, there are multiple methods for creating a tuple.

They are listed in the following order:

  1. By using Parentheses()
  2. With just one item
  3. Tuple Constructor

Read More - 50 Python Interview Questions

1. By using Parentheses()

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

Example of Creating a Tuple in Python using Parenthesis()

scholarhat_articles = ("C", "C++", "Python", "Java")
print(scholarhat_articles)

Explanation:

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]}")

Explanation:

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 a Tuple in Python using the Tuple Constructor

my_list = ["apple", "banana", "cherry"]
my_tuple = tuple(my_list)
print(f"List: {my_list}")
print(f"Tuple: {my_tuple}")

Explanation:

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. It uses strings toprint the list and the tuple along with relevant messages.

Output

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

Tuple vs list in Python:

FeatureTupleList
MutabilityImmutable (cannot be changed after creation)Mutable (can be changed after creation)
Syntax() (e.g., my_tuple = (1, 2, 3))[] (e.g., my_list = [1, 2, 3])
PerformanceFaster (due to immutability and fixed size)Slower (overhead for dynamic resizing)
Use casesFixed or constant data (e.g., coordinates, settings)Dynamic data that may change (e.g., items in a cart)
HashableYes, if all elements are hashable (can be used as dict keys)No, lists are unhashable and cannot be used as dict keys
ExampleDatabase records, function returnsCollections of items to modify or iterate over

Built-in Functions for Tuples

Python provides various built-in functions for doing operations with tuples

1. len(tuple): len() method returns the length of the tuple


t = (1, 2, 3)
print(len(t))

Output: 5

2.max(tuple): The max() method returns the value of the maximum item in the tuple


t = (1, 5, 3)print(max(t)) 

Output: 5

3.min(tuple): The min() method returns the value of the minimum item in the tuple


t = (1, 5, 3)
print(min(t)) 

Output: 1

4.sum(tuple): The sum() method returns the sum of all items in the tuple


t = (1, 2, 3)
print(sum(t)) 

Output: 6

5.any(tuple): any() method returns the if any item in the tuple is true

t = (0, False, 3)
print(any(t))

Output: True (because of 3)

6.all(tuple): all() method returns true if all items in the tuple are true


t = (0, False, 3)
print(all(t))

Output: False

Tuple Operations in Python with Examples

1. How to Access Tuple Elements in Python

Accessing items in a tuple in Python is done using indexing, similar to lists. Tuples are ordered sequences, and each item has a numerical index starting from 0 for the first item. You can use these indices within square brackets to retrieve specific elements.

    Example of Accessing Tuple Elements in Python

    my_tuple=(1,2,3,4)
    print(my_tuple[0],end=" ") #print first item (positive indexing)
    print(my_tuple[-1]) #print last item (negative indexing)
    

    Explanation:

    • my_tuple[0] accesses the first item of the tuple (1) using positive indexing.
    • my_tuple[-1] accesses the last item of the tuple (4) using negative indexing.

    Output

    
    1 4

    2. Slicing in Tuple

    Tuple slicing in Python allows the extraction of a portion of a tuple, creating a new tuple containing the selected elements. This operation is performed using the slicing operator [] with the syntax [start:stop:step].

    Example of Updating Tuples in Python

    my_tuple=(1,2,3,4)
    print(my_tuple[0:3],end=" ") #print item 1,2,3
    print(my_tuple[1:3]) #print item 2,3
    
    

    Explanation:

    • my_tuple[0:3] slices the tuple from index 0 to 2 (last index is exclusive), returning (1, 2, 3).
    • my_tuple[1:3] slices from index 1 to 2, returning (2, 3).

    Output

    123 23

    3. Unpacking the value of a tuple

    Unpacking a tuple means extracting the value of an n-size tuple into n different variables.

    Example of unpacking the value of a tuple in Python Editor

    my_tuple=(1,2,3,4)
    a,b,c,d = my_tuple
    print(a,end=" ") # print 1
    print(b,end=" ") # print 2
    print(c,end=" ") # print 3
    print(d,end=" ") # print 4
    

    Explanation:

    • Each element in my_tuple is assigned to a separate variable:
    • a = 1, b = 2, c = 3, d = 4.

    Output

    1 2 3 4

    4. Concatenation of a tuple

    In Python, tuples can be concatenated using the + operator. This operation creates a new tuple containing all elements from the original tuples in the order they were concatenated.

    Example of concatenation a tuple in Python Editor

    my_tuple1=(1,2,3)
    my_tuple2=(4,5,6)
    my_tuple3=my_tuple1+my_tuple2
    	print(my_tuple3) #print 1,2,3,4,5,6
    

    Explanation:

    • The + operator joins the two tuples into a new one:
    • (1, 2, 3) + (4, 5, 6) → (1, 2, 3, 4, 5, 6).

    Output

    1,2,3,4,5,6

    3. Deleting a tuple in Python

    Tuples in Python are immutable, which means their elements cannot be changed, added, or removed after the tuple has been created. Therefore, it is not possible to delete individual elements from a tuple.

    Example of unpacking the value of a tuple in Python Editor

    my_tuple=(1,2,3)
    del my_tuple
    

    Explanation:

    • The del keyword deletes the entire tuple from memory.
    • After this, using my_tuple will raise an error as it no longer exists.

    Output

    1 2 3 4

    Practical Use Cases

    1. Swapping Variables:
    
    x, y = 10, 20
    x, y = y, x  # Swaps the values
    print(x, y)  # Output: 20 10
    
    2. Returning Multiple Values from a Function:
    
    def get_point():
        return 1, 2
    
    x, y = get_point()
    print(x, y)  # Output: 1 2
    These concepts make Python code more readable and efficient, especially when working with multiple values.
    

    These concepts could improve the readability and effectiveness of Python code, particularly when handling many values.

    4. Returning Tuples From Functions

    Python practices frequently return tuples, especially when you wish the function to return numerous values. Tuples are a great option for returning a set of related data because they may hold several immutable elements.

    Basic Example

    Here's how you can return a tuple from a function:
    def get_coordinates():
        x = 10
        y = 20
        return x, y  # Returns a tuple (10, 20)
    
    coordinates = get_coordinates()
    print(coordinates)  # Output: (10, 20)
    
    In this example, the get_coordinates function returns a tuple containing the values of x and y.

    Unpacking Returned Tuples

    You can unpack the returned tuple directly when calling the function:
    def get_coordinates():
        x = 10
        y = 20
        return x, y  # Returns a tuple (10, 20)
    
    x, y = get_coordinates()
    print(x)  # Output: 10
    print(y)  # Output: 20
    
    In this case, the tuple (10, 20) returned by get_coordinates is unpacked into the variables x and y.

    Returning Multiple Values

    Returning a tuple is handy when a function needs to return multiple values of different types:

    def analyze_data(data):
        mean = sum(data) / len(data)
        minimum = min(data)
        maximum = max(data)
        return mean, minimum, maximum  # Returns a tuple (mean, min, max)
    
    data = [4, 8, 15, 16, 23, 42]
    mean, minimum, maximum = analyze_data(data)
    
    print("Mean:", mean)          # Output: Mean: 18.0
    print("Minimum:", minimum)    # Output: Minimum: 4
    print("Maximum:", maximum)    # Output: Maximum: 42
    
    Returning Tuples with *args or **kwargs You can also return tuples when using *args or **kwargs in functions, which allows for more dynamic argument handling:
    def process_args(*args):
        return args  # Returns a tuple of all arguments
    result = process_args(1, 2, 3, "Python", True)
    print(result)  # Output: (1, 2, 3, 'Python', True)
    

    Realistic Use Cases

    • Multiple Results: Functions that do calculations and provide a number of related results.
    • Efficient Data managing: Combining several return values into a tuple to make managing them easier.
    • Data Transformation: Data transformation refers to operations, including unit conversions and coordinate conversions, that require the return of altered data in pairs.

    5. Creating Copies of a Tuple: Using the Copy Module

    You can use the copy module to make a copy of a tuple, even though it's more frequently used for copying lists or other mutable objects. The copy() function will essentially do the same operations as the tuple() constructor or slicing because tuples are immutable.
    import copy
    
    original_tuple = (1, 2, 3)
    copied_tuple = copy.copy(original_tuple)
    
    print(copied_tuple)  # Output: (1, 2, 3)
    

    Output

    (1, 2, 3)
    

    6. Concatenating and Repeating Tuples

    Tuples in Python are easily concatenated and repeated with the use of basic operators. Here's how to accomplish it:

    1. Concatenating Tuples

    tuple1 = (1, 2, 3)
    tuple2 = (4, 5, 6)
    
    concatenated_tuple = tuple1 + tuple2
    print(concatenated_tuple)  # Output: (1, 2, 3, 4, 5, 6)
    

    Output

    (1, 2, 3, 4, 5, 6)
    
    Tuple1 and Tuple2 are concatenated in this example to create a new tuple called concatenated_tuple, which contains every element from both tuples.

    2. Repeating Tuples

    The * operator repeats a tuple a given number of times, which is useful for repeating its elements.
    tuple1 = (1, 2, 3)
    
    repeated_tuple = tuple1 * 3
    print(repeated_tuple)  # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
    

    Output

    (1, 2, 3, 1, 2, 3, 1, 2, 3)
    
    The new tuple, repeated_tuple, is the outcome of tuple1 being repeated three times in this case.
    Summary
    Python Tuples are lightweight, faster than lists, and ideal for fixed collections of data like coordinates, dates, or constant values. With support for indexing, slicing, nesting, and iteration, tuples offer flexibility while ensuring data integrity. Understanding when and how to use tuples can help you write more efficient, readable, and error-resistant Python code. To learn more about these topics, join our Python certification course.

    FAQs

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

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

    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.

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

    Take our Python skill challenge to evaluate yourself!

    In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

    GET FREE CHALLENGE

    Share Article
    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.

    Live Training - Book Free Demo
    Azure AI Engineer Certification Training
    17 Jul
    07:00AM - 09:00AM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    Accept cookies & close this