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:
print(colors[0])
: This line uses theprint()
function to display the element at index 0 of thecolors
tuple. In Python, indexing starts at 0, socolors[0]
refers to the first element of the tuple. In this case, it prints "red" to the console.print(colors[1])
: Similarly, this line prints the element at index 1 of thecolors
tuple, which is "green."print(colors[2])
: This line prints the element at index 2 of thecolors
tuple, which is "blue."
Therefore, you get the below output.
Example 2
Type the below code into your code editor.
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.
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 integer35
.city
will contain the string "Gotham City."
Printing the Output:
. The
print()
statements display the values of the variables'name
,age
, andcity
.. 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.