Python Tuples: The Unbreakable Bonds of Data (No Breakups Allowed!)

Photo by RetroSupply on Unsplash

Python Tuples: The Unbreakable Bonds of Data (No Breakups Allowed!)

·

2 min read

Table of contents

A Python Tuple is a collection of ordered elements, similar to a list. Tuples are immutable, which means once you create a tuple, you cannot change its elements or their order. In contrast, lists are mutable, and you can add, remove, or modify elements in a list. Tuples are defined using parentheses () while lists use square brackets [] as shown below.

The final output will take the following appearance:

Example 1

Kindly input the following code into your code editor for review and further analysis.

A tuple named colors and explicitly specifies its type as a tuple using type hinting (: tuple). While Python is dynamically typed and doesn't require explicit type annotations, including them can be beneficial for code documentation and type-checking tools.

The code then proceeds to access and print elements from the colors tuple using square bracket indexing, just as explained in the previous response. The print lines are responsible for printing the individual elements of the colors tuple to the console. Let's break down what each line does:

  1. print(colors[0]): This line uses the print() function to display the element at index 0 of the colors tuple. In Python, indexing starts at 0, so colors[0] refers to the first element of the tuple. In this case, it prints "red" to the console.

  2. print(colors[1]): Similarly, this line prints the element at index 1 of the colors tuple, which is "green."

  3. print(colors[2]): This line prints the element at index 2 of the colors tuple, which is "blue."

Therefore, you get the below output.

Example 2

Type the below code into your code editor.

  1. Creating a Tuple with Mixed Data Types.

    In this line, a tuple named person is created with three elements of different data types:

    • "Bruce Wayne" (a string) represents the person's name.

    • 35 (an integer) represents the person's age.

    • "Gotham City" (a string) represents the person's city.

  2. Tuple Unpacking:

    These lines use tuple unpacking to assign the values stored in the person tuple to individual variables. Specifically:

    • name will contain the string "Bruce Wayne."

    • age will contain the integer 35.

    • city will contain the string "Gotham City."

  3. Printing the Output:

    . The print() statements display the values of the variables' name, age, and city.

    . Each print() statement outputs the respective value assigned to the variable.

    When you run this corrected code, it will produce the following output:

    Concluding today's discussion, we will delve into Python sets in our upcoming article.