In this article we will find out if all the tuples in a given list are of same length.
With len
We will use len function and compare its result to a given value which we are validating. If the values are equal then we consider them as same length else not.
Example
listA = [('Mon', '2 pm', 'Physics'), ('Tue', '11 am','Maths')]
# printing
print("Given list of tuples:\n", listA)
# check length
k = 3
res = 1
# Iteration
for tuple in listA:
if len(tuple) != k:
res = 0
break
# Checking if res is true
if res:
print("Each tuple has same length")
else:
print("All tuples are not of same length")Output
Running the above code gives us the following result −
Given list of tuples:
[('Mon', '2 pm', 'Physics'), ('Tue', '11 am', 'Maths')]
Each tuple has same lengthWith all and len
We sue the len function alogn with the all function and use a for loop to iterate through each of the tuple present in the list.
Example
listA = [('Mon', '2 pm', 'Physics'), ('Tue', '11 am','Maths')]
# printing
print("Given list of tuples:\n", listA)
# check length
k = 3
res=(all(len(elem) == k for elem in listA))
# Checking if res is true
if res:
print("Each tuple has same length")
else:
print("All tuples are not of same length")Output
Running the above code gives us the following result −
Given list of tuples:
[('Mon', '2 pm', 'Physics'), ('Tue', '11 am', 'Maths')]
Each tuple has same length