- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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
Advertisements