Python Tuple Methods
Namya Shah
2 min read
A tuple is an immutable list of values.
# Both are same
t1 = ('a', 'b', 'c')
t1 = 'a', 'b', 'c'
NOTE THAT
A single value in parentheses is not a tuple
To create a single value tuple it is necessary to have a trailing comma.
a = ('b') # Not a tuple, it is a value assigned to variable a
a = ('b',) # A single value tuple and not a value assigned to variable a
len()
The function len returns the total length of the tuple
t1 = (1,2,3,4)
len(t1)
# 4
max() and min() function
Returns with max or min data type available in tuple.
t1 = (1,2,3,4)
max(t1)
#4
min(t1)
#1
tuple()
Converts a list to tuple.
l1 = [1,2,3,4]
tuple(l1)
# (1,2,3,4)
Tuple Concatenation
We can use ‘+’ sign to add two tuples
t1 = (1,2,3,4)
t2 = (5,6,7,8)
t3 = t1+t2
print(t3)
# t3 = (1,2,3,4,5,6,7,8)
Reverse a tuple
marvel = ("iron man", "thor", "hulk", "captain america")
reverse_marvel = marvel[::-1]
# [::-1] = [0:0:-1]
print(reverse_marvel)
# ("captain america", "hulk", "thor", "iron man")
The number of times a specific value appeared in tuple
a = (1,2,3,4,5,6,7,8,9,1,2,3,4,5,1)
b = a.count(1)
print(b)
# 3
Finding index of a specified value in the tuple
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.index(8)
print(x)
# 3
0
Subscribe to my newsletter
Read articles from Namya Shah directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Namya Shah
Namya Shah
I am a developer who is very enthusiast about technology and coding.