Tuples in Python with Examples - A Beginner Guide

Tuples in Python with Examples - A Beginner Guide

21 Aug 2024
Beginner
7.31K Views
36 min read

Python Tuples

Python tuples are immutable sequences that are used to hold several things in a single variable. They are similar to lists but have one important difference like tuples once created, they cannot be altered. By putting values inside parenthesis and separating them with commas, you can build a tuple. Tuples are frequently used to group similar data together and support a variety of techniques and actions, including concatenation, slicing, and indexing. Tuples are generally used when the data shouldn't be changed, as opposed to lists.

In this Python Tutorial, we'll look at what makes tuples so special and how to define them in Python. We'll also explore different tuple operations in Python with examples and some clever ways to use them in your programming projects. So, if you're ready to get coding with Python's most infamous structure, let's start together!

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

1. Pythons Tuple's Data Type

The most basic sequence that Python has to offer is most likely the built-in tuple data type. Tuples have a fixed amount 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'

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

Output

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

Tuple Operations

1. 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:

    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

    2. 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')

    3. 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')

    Other 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

      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.

        6 Usages of Tuples in Python

        1. Retrieving Multiple Items From a Tuple: Slicing
        2. Tuple Immutability
        3. Packing and Unpacking Tuples
        4. Returning Tuples From Functions
        5. Creating Copies of a Tuple
        6. Concatenating and Repeating Tuples

        1. Retrieving Multiple Items

        • Tuples can also be used to extract a section or slice of its content using the slicing operation, which has the same syntax as regular Python sequences
        • This construct's [start:stop:step] component is referred to as the slicing operator. It is composed of three optional indices (start, stop, and step) and two square brackets. There is also an optional second colon. It is usually reserved for situations in which you require a step value other than 1.
        • The slicing operator's indices are all optional. 

        Their default values and meanings are summarized as follows:

        Retrieving Multiple Items From a Tuple: Slicing

        These indices can be combined in many ways to extract particular parts of a given tuple. Here are some examples of slicing :

        1. Basic Slicing

        # Define a tuple
        my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
        
        # Slice from index 2 to 5 (exclusive)
        slice1 = my_tuple[2:6]
        print(slice1)  # Output: (3, 4, 5, 6)
        

          Output

          (3, 4, 5, 6)
          

          2. Slicing with a Step

          # Slice from index 1 to 8 with a step of 2
          my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
          slice2 = my_tuple[1:9:2]
          print(slice2)  # Output: (2, 4, 6, 8)
          

          Output

          (2, 4, 6, 8)
          

          3. Omitting Start or End

          # Define a tuple
          my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
          # Slice from the beginning to index 4 (exclusive)
          slice3 = my_tuple[:5]
          print(slice3)  # Output: (1, 2, 3, 4, 5)
          
          # Slice from index 5 to the end
          slice4 = my_tuple[5:]
          print(slice4)  # Output: (6, 7, 8, 9, 10)
          

          Output

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

          4. Negative Indexing

          # Define a tuple
          my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
          # Slice using negative indices
          slice5 = my_tuple[-5:-1]
          print(slice5)  # Output: (6, 7, 8, 9)
          
          # Slice using negative step to reverse
          slice6 = my_tuple[::-1]
          print(slice6)  # Output: (10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
          

          Output

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

          5. Full Slice

          # Define a tuple
          my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
          # Full slice to create a copy of the tuple
          slice7 = my_tuple[:]
          print(slice7)  # Output: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
          

          Output

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

          2. Tuple Immutability

          Tuples in Python cannot have their contents changed once they have been generated, as they are immutable. This tuple property suggests that updating specific components within an already-existing tuple cannot be done using indices
          my_tuple = (10, 20, 30)
          try:
              my_tuple[0] = 100  # Trying to change the first element
          except TypeError as e:
              print(e)  # Output: 'tuple' object does not support item assignment
          
          # However, you can create a new tuple
          new_tuple = my_tuple[:2] + (100,)
          print(new_tuple)  # Output: (10, 20, 100)
          

          Output

          'tuple' object does not support item assignment
          (10, 20, 100)
          

          Key Points of Tuple Immutability:

          • You cannot modify the elements of a tuple after its creation.
          • Attempting to change an element of a tuple will result in a TypeError
          • You cannot add new elements to a tuple or remove existing ones.
          • Methods like append(), remove(), and pop() are not available for tuple
          • While the tuple itself is immutable, if it contains mutable objects like lists, the contents of those objects can be modified.
          • To "modify" a tuple, you have to create a new tuple by concatenating or slicing existing tuples.

          3. Packing and Unpacking Tuples

          1. Packing Tuples

          The technique of integrating several values into a single tuple is known as packing tuples.
          # Packing values into a tuple
          my_tuple = 1, 2, 3
          print(my_tuple)  # Output: (1, 2, 3)
          
          # Packing with parentheses (optional but clearer)
          my_tuple = (1, 2, 3)
          print(my_tuple)  # Output: (1, 2, 3)
          

          Output

          (1, 2, 3)
          (1, 2, 3)
          

          In the example above, 1, 2, and 3 are packed into the tuple my_tuple.

          2. Unpacking Tuples

          Extracting values from a tuple and allocating them to distinct variables is the opposite of unpacking a tuple.
          # Unpacking a tuple
          my_tuple = (1, 2, 3)
          a, b, c = my_tuple
          
          print(a)  # Output: 1
          print(b)  # Output: 2
          print(c)  # Output: 3
          

          Output

          1
          2
          3
          

          The tuple my_tuple is unpacked into variables a, b, and c in the above example.

          Using the * Operator for unpacking:The * operator can also be used to unpack tuples, allowing you to capture multiple items in a list.

          my_tuple = (1, 2, 3, 4, 5)
          
          # Unpacking with the * operator
          a, *b, c = my_tuple
          
          print(a)  # Output: 1
          print(b)  # Output: [2, 3, 4]
          print(c)  # Output: 5
          

          Output

          1
          [2, 3, 4]
          5
          

          In this case, the initial value is taken by a, the last value is taken by c, and the middle values are stored in a list called b.

          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
          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 of the realm of tuples using Python. Also, proper Python Certification Training can make life easier for developers by enabling them to store and access data efficiently.

          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.

          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.

          Accept cookies & close this