Python Tuples With Example

In Python, a tuple is an ordered collection of elements, similar to a list. However, tuples are immutable, meaning their values cannot be modified once they are created. This makes them useful for situations where you want to ensure that certain data remains constant and unchanged throughout your program.

Here’s an example of how to create a tuple in Python:

my_tuple = (1, 2, 3, "four", 5.0)

In this example, we’ve created a tuple called my_tuple that contains five elements: the integers 1, 2, and 3, the string “four”, and the float 5.0. Note that we enclosed the elements in parentheses, and separated them with commas.

We can access individual elements of a tuple using indexing, just like we can with a list:

print(my_tuple[0])   # Output: 1
print(my_tuple[3])   # Output: four

We can also use slicing to access a range of elements:

print(my_tuple[1:4])   # Output: (2, 3, 'four')

One thing to note about tuples is that even though they are immutable, you can still create a new tuple that contains the same elements as an existing tuple, and assign it to the same variable. For example:

my_tuple = (1, 2, 3)
my_tuple = my_tuple + (4, 5)
print(my_tuple)   # Output: (1, 2, 3, 4, 5)

In this example, we’ve created a new tuple that consists of the elements in my_tuple plus the elements 4 and 5. We then assigned this new tuple to the variable my_tuple, effectively replacing the original tuple with the new one.

I hope that helps! Let me know if you have any other questions.

Leave a Reply