Common Tuple Methods in Python
Tuples in Python come with a few built-in operations that allow you to retrieve information and manipulate them indirectly. Here are some key methods:
len(t)
: returns the number of elements in tuplet
;t * n
: createsn
repetitions of tuplet
;t.count(x)
: counts how oftenx
appears int
.
Since tuples are immutable, you might wonder: How do I add or modify elements in a tuple? Unlike lists, tuples do not support methods like .append()
or .extend()
for adding elements directly. However, there is a workaround called tuple concatenation.
tuple1 + tuple2
: merges two tuples (both must be tuples).
# Initial tuple US_Info = ("USA", 9629091, 331002651) # New data US_Info_new = ("Washington D.C.", 50) # Concatenate two tuples and save the result US_Info_upd = US_Info + US_Info_new print(US_Info_upd)
Thanks for your feedback!