What are Tuples in Python and How to Use Them?

Tuples in Python are immutable sequences used to store collections of items. They are similar to lists but cannot be changed after creation.

Creating a Tuple

You can create a tuple by enclosing elements in parentheses:

my_tuple = (1, 2, 3)

Or without parentheses:

my_tuple = 1, 2, 3

Accessing Tuple Elements

Use indexing to access elements:

print(my_tuple[0])  # Output: 1

Immutable Nature

Tuples cannot be modified:

my_tuple[0] = 10  # This will raise a TypeError

Tuple Unpacking

You can unpack tuple elements into variables:

a, b, c = my_tuple
print(a, b, c)  # Output: 1 2 3

When to Use Tuples

  • Fixed Data: When the data should not change.
  • Dictionary Keys: Tuples can be used as keys due to their immutability.
  • Function Returns: Return multiple values from a function.

Conclusion

Tuples are an essential data structure in Python for storing immutable sequences of data. Understanding tuples enhances your ability to write efficient and secure code.

Leave a Reply

Your email address will not be published. Required fields are marked *