Python Tuple
Both tuples and lists are ways to store multiple items in a single variable.
BUT they have one big difference:
📦 1️⃣ Lists
-
Use: Square brackets
[ ]
-
Can change: ✅ Yes! You can add, remove, or change items.
-
Example:
🗂️ 2️⃣ Tuples
-
Use: Parentheses
( )
-
Can change: ❌ No! Once you make it, it stays the same. You cannot add, remove, or change items.
-
Example:
🗝️ Key difference:
List | Tuple | |
---|---|---|
How to write | [1, 2, 3] | (1, 2, 3) |
Can change? | ✅ Yes | ❌ No |
When to use | When you need to update data | When you want it to stay the same |
🎓 Simple analogy:
-
List: Like a backpack — you can put stuff in, take stuff out.
-
Tuple: Like a sealed box — once packed, you don’t open it.
✅ In short:
-
Use lists for flexible, changing collections.
-
Use tuples for fixed, unchangeable collections.
max()
The built-in function max() returns the tuple’s maximum value. Note that this function requires all of the values to be of the same data type. If used with numerical values, the function returns the maximum value. If used with string values, the function returns the value at the tuple’s maximum index as if it was sorted alphabetically. The string closer to the letter “Z” in the alphabet would have a higher index.
my_tuple = (65, 2, 88, 101, 25)
max(my_tuple) # returns 101
my_tuple = ('orange', 'blue', 'red', 'green')
max(my_tuple) # returns "red"
my_tuple = ('abc', 234, 567, 'def')
max(my_tuple) # throws an error!
min()
The built-in function min() returns the tuple’s minimum value. Similar to the max() function, the min() function requires all of the values to be of the same data type. If used with numerical values, the function returns the minimum value. If used with string values, the function returns the value at the tuple’s minimum index as if it was sorted alphabetically. The string closer to the letter “A” in the alphabet would have a lower index.
my_tuple = (65, 2, 88, 101, 25)
min(my_tuple) # returns 2
my_tuple = ('orange', 'blue', 'red', 'green')
min(my_tuple) # returns "blue"
my_tuple = ('abc', 234, 567, 'def')
min(my_tuple) # throws an error!
.index()
The built-in method `.index()’ takes in a value as the argument to find its index in the tuple.
my_tuple = ('abc', 234, 567, 'def')
my_tuple.index('abc') # returns 0
my_tuple.index(567) # returns 2
.count()
The built-in method `.count()’ takes in a value as the argument to find the number of occurrences in the tuple.
my_tuple = ('abc', 'abc', 2, 3, 4)
my_tuple.count('abc') # returns 2
my_tuple.count(3) # returns 1
Comments
Post a Comment