Methods for working with tuples
Methods for working with tuples are similar to methods for working with lists, except for methods that change the tuple. Such methods are not available due to the immutability of the tuple. They can be applied by creating a new tuple.
Tuple sort example
You can easily sort a tuple using the
sorted()
function.
1
2
3
4
|
a = (5, 3, 2, 1, 4)
print(sorted(a)) # [1, 2, 3, 4, 5]
a = tuple(sorted(a))
print(a) # (1, 2, 3, 4, 5)
|
Note that methods such as
append()
,
extend()
,
remove()
do NOT work with tuples
and
pop()
.