Tuples in Python
Tuples
51
Sure! In Python, a tuple is a collection of ordered, immutable elements.
This means that once you create a tuple, you cannot add or remove elements from it. Tuples are commonly used to group related data together.
Here's an example of how to create a tuple:
my_tuple = (1, "hello", 3.14)
In this example, the my_tuple
variable contains three elements: an integer (1
), a string ("hello"
), and a float (3.14
).
One of the main benefits of tuples is that they are faster than lists, so if you have a collection of data that you don't need to modify, using a tuple instead of a list can help your program run more efficiently.
You can access individual elements of a tuple using indexing, just like with lists:
print(my_tuple[0]) # output: 1 print(my_tuple[1]) # output: "hello" print(my_tuple[2]) # output: 3.14
You can also use slicing to access a range of elements:
print(my_tuple[1:]) # output: ("hello", 3.14)
Lastly, you can unpack a tuple into individual variables:
a, b, c = my_tuple print(a) # output: 1 print(b) # output: "hello" print(c) # output: 3.14
I hope that helps! Let me know if you have any other questions.
March 25, 2023