Understanding Tuples in Python with Examples.
Tuple in Python – Definition, Examples, and Operations
In Python, a tuple is one of the built-in data types used to store a collection of items. Tuples are similar to lists, but there is one key difference: tuples are immutable, which means their values cannot be changed after creation.
What is a Tuple?
A tuple is an ordered collection of elements enclosed in parentheses ( ) and separated by commas.
Syntax
Example
Output:
Characteristics of Tuples
-
Ordered (items have a fixed position)
-
Immutable (cannot be modified)
-
Allows duplicate values
-
Can store different data types
-
Faster than lists (performance benefit)
Tuple with Different Data Types
Accessing Tuple Elements
You can access tuple elements using indexing.
Tuple Operations
1. Length of Tuple
2. Concatenation
3. Repetition
4. Membership
Why Tuple Modification is Not Possible
Tuples are immutable, so you cannot add, remove, or change elements directly.
Example (This will cause an error ❌)
Error:
How to Modify a Tuple (Convert to List)
If you want to add or modify elements, you must convert the tuple into a list, make changes, and then convert it back to a tuple.
Example: Add an Element
Output:
When to Use Tuples
-
When data should not change
-
To protect data from accidental modification
-
When using fixed records (like coordinates, days, months)
-
For better performance than lists
Conclusion
A tuple is a powerful and efficient data type in Python when you need a fixed collection of items. Since modification is not possible, converting it into a list is the correct way if changes are required.
Comments
Post a Comment