Common Tuple Methods :



1. count(value)

fruits = ("apple", "banana", "cherry", "banana")
print(fruits.count("banana"))  # Output: 2


2. index(value)

fruits = ("apple", "banana", "cherry")
print(fruits.index("banana"))  # Output: 1


3. len( )

fruits = ("apple", "banana", "cherry")
print(len(fruits))  # Output: 3


4. max( ) and min( )

my_tuple = (5, 10, 25, 2)
print(max(my_tuple))  # Output: 25
print(min(my_tuple))  # Output: 2


5. sum( )

my_tuple = (5, 10, 25, 2)
print(sum(my_tuple))  # Output: 42


5. sorted( )

my_tuple = (5, 10, 25, 2)
print(sorted(my_tuple))  # Output: [2, 5, 10, 25]


6. tuple( )

my_list = [5, 10, 25, 2]
my_tuple = tuple(my_list)
print(my_tuple)  # Output: (5, 10, 25, 2)


7. Tuple Unpacking

my_tuple = (5, 10, 25, 2)
a, b, c, d = my_tuple
print(a, b, c, d)  # Output: 5 10 25 2


8. Asterisk(*)

my_tuple = (5, 10, 25, 2)
a, b, *c = my_tuple
print(a, b, c)  # Output: 5 10 [25, 2]


9. join( )

my_tuple = ("apple", "banana", "cherry")
result = ", ".join(my_tuple)
print(result)  # Output: "apple, banana, cherry"


10. Multiply

my_tuple = (5, 10, 25, 2)
result = my_tuple * 2
print(result)  # Output: (5, 10, 25, 2, 5, 10, 25, 2)


11. remove(value)

my_tuple = ("apple", "banana", "cherry", "banana")
my_tuple = tuple(x for x in my_tuple if x != "banana")
print(my_tuple)  # Output: ('apple', 'cherry')


12. Range of Indexes

my_tuple = (5, 10, 25, 2)
print(my_tuple[1:3])  # Output: (10, 25)


13. Negative Indexing

my_tuple = (5, 10, 25, 2)
print(my_tuple[-1])  # Output: 2
print(my_tuple[-3:-1])  # Output: (10, 25)


When to Use Tuples?

Use tuples when:



Summary



Difference between List and Tuple:


Feature List Tuple
Syntax list1 = [1, 2, 3] tuple1 = (1, 2, 3)
Mutability Mutable (can be changed) Immutable (cannot be changed)
Methods Many built-in methods (append, remove, etc.) Fewer built-in methods (count, index)
Performance Slower than tuples Faster than lists
Use Case When data may change When data should not change
Brackets Square brackets [ ] Parentheses ( )
Can be used as dictionary key? No Yes (if all elements are immutable)