Python Tuple
In Python, a tuple is similar to a list, but it is immutable, meaning that you cannot modify its contents once it has been created. Tuples are often used to represent fixed collections of related data, such as a date or a point in two-dimensional space.
Here's an example of how to create a tuple in Python:
refer to:theitroad.commy_tuple = (1, 2, 3, "four", 5.0)
In this example, we've created a tuple with five elements: the integers 1, 2, and 3, the string "four", and the floating-point number 5.0.
You can access elements of a tuple using the same indexing syntax as with lists:
print(my_tuple[0]) # prints 1 print(my_tuple[3]) # prints "four"
You can also use negative indexing to access elements from the end of the tuple:
print(my_tuple[-1]) # prints 5.0 print(my_tuple[-2]) # prints "four"
Because tuples are immutable, you cannot add or remove elements from them. However, you can create a new tuple by concatenating two or more tuples:
new_tuple = my_tuple + (6, 7, 8)
This creates a new tuple containing the elements of the original tuple, followed by the integers 6, 7, and 8.
You can also use tuple unpacking to assign the elements of a tuple to individual variables:
a, b, c, d, e = my_tuple
This assigns the first five elements of the tuple to the variables a
, b
, c
, d
, and e
, respectively.
These are just a few examples of the many ways that you can work with tuples in Python. Tuples are a useful data type when you need to represent a fixed collection of related data that should not be modified.