count()
, index()
, sorted()
, and reversed()
.my_tuple = (1, 2, 3, 4, 5)
print(my_tuple.count(3)) # Output: 1
print(my_tuple.index(2)) # Output: 1
sorted_tuple = sorted(my_tuple)
print(sorted_tuple) # Output: [1, 2, 3, 4, 5]
reversed_tuple = list(reversed(my_tuple))
print(reversed_tuple) # Output: [5, 4, 3, 2, 1]
count()
, index()
, sorted()
, reversed()
, immutability.student_scores = ((10, 'John'), (9, 'Alice'), (8, 'Bob'), (10, 'John'))
score_counts = {score: 0 for score in range(12)}
for student, score in student_scores:
score_counts[score] += 1
sorted_students = sorted(student_scores, key=lambda x: x[0])
print(score_counts) # Output: {8: 1, 9: 1, 10: 2}
print(sorted_students) # Output: [(8, 'Bob'), (9, 'Alice'), (10, 'John'), (10, 'John')]
sorted()
method.What causes it: Attempting to change a tuple element or assigning a new value to a tuple variable.
# Bad code example that triggers the error
my_tuple = (1, 2, 3)
my_tuple[0] = 0 # TypeError: 'tuple' object does not support item assignment
my_tuple = (4, 5, 6) # TypeError: 'tuple' object does not support item assignment
Error message:
Traceback (most recent call last):
File "example.py", line X, in <module>
error_code_here
TypeError: 'tuple' object does not support item assignment
Solution: Use lists instead of tuples when you need to change the values or add new elements.
# Corrected code
my_list = [1, 2, 3]
my_list[0] = 0
print(my_list) # Output: [0, 2, 3]
my_list.append(4)
print(my_list) # Output: [0, 2, 3, 4]
Why it happens: Tuples are immutable, so you cannot change their elements or assign new values to them.
How to prevent it: Use lists when you need to modify the data or work with mutable collections.
What causes it: Referencing a non-existent tuple variable.
# Bad code example that triggers the error
print(non_existent_tuple) # NameError: name 'non_existent_tuple' is not defined
Error message:
Traceback (most recent call last):
File "example.py", line X, in <module>
print(non_existent_tuple)
NameError: name 'non_existent_tuple' is not defined
Solution: Define the tuple variable before using it.
# Corrected code
my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)
Why it happens: You are trying to access a tuple variable that has not been defined.
How to prevent it: Define the tuple variable before using it or use from module import tuple_name
if the variable is in another module.
namedtuple()
.count()
, index()
, sorted()
, and reversed()
.