Tuples in Python

Tuples

Tuples are same as lists are with the exception that the data once entered into the tuple cannot be changed no matter what.

Creating a Tuple

You can create a tuple using parenthesis or using the tuple() function.

# Creating a tuple
my_tuple = (1, 2, 3)
print(my_tuple)

# Output:
# (1, 2, 3)

Accessing Elements

Accessing elements is the same as it is for accessing values in lists.

my_tuple2 = (1, 2, 3, 'python')

# Accessing elements
for x in my_tuple2:
    print(x)
    
print(my_tuple2)
print(my_tuple2[0])
print(my_tuple2[:])
print(my_tuple2[3][4])

# Output:
# 1
# 2
# 3
# python
# (1, 2, 3, 'python')
# 1
# (1, 2, 3, 'python')
# o

Appending Elements

To append the values, you use '+' operator which will take another tuple to be appended to it.

my_tuple = (1, 2, 3)
my_tuple = my_tuple + (4, 5, 6)  # add elements
print(my_tuple)

# Output:
# (1, 2, 3, 4, 5, 6)

Note: Since tuples are immutable, we're not actually modifying the original tuple. Instead, we're creating a new tuple with the combined elements and reassigning the variable.