Syntax error Find whether all tuple have same length in Python

Find whether all tuple have same length in Python



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

 Live Demo

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 length

With 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

 Live Demo

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
Updated on: 2020-06-04T11:57:20+05:30

265 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements