Python tuple

A Python tuple is a collection of elements that is immutable, meaning its values cannot be changed after it is created. Tuples are defined by enclosing elements in parentheses
()
. Here is an example of creating and accessing elements in a tuple:

# Creating a tuple
my_tuple = (1, 2, "hello", 3.14)

# Accessing elements in a tuple using indexing
print(my_tuple[0])  # Output: 1
print(my_tuple[2])  # Output: hello

# Slicing a tuple
print(my_tuple[1:3])  # Output: (2, "hello")

# Tuple unpacking
a, b, c, d = my_tuple
print(a)  # Output: 1
print(b)  # Output: 2
print(c)  # Output: hello
print(d)  # Output: 3.1
In the example above, we create a tuple
my_tuple
with different types of elements. We then access elements using indexing, slice the tuple, and demonstrate tuple unpacking to assign individual values to variables.
Stephen Olubanji Akinpelu

Previous Post Next Post