Python | Find whether all tuple have same length
Given a list of tuples, the task is to find whether all tuple have same length.
Below are some ways to achieve the above task.
Method #1: Using Iteration
# Python code to find whether all # tuple have equal length # Input List initialization Input = [( 11 , 22 , 33 ), ( 44 , 55 , 66 )] # printing print ( "Initial list of tuple" , Input ) # K Intilization k = 3 flag = 1 # Iteration for tuple in Input : if len ( tuple ) ! = k: flag = 0 break # Checking whether all tuple # have length equal to 'K' in list of tuple if flag: print ( "All tuples have same length" ) else : print ( "Tuples does not have same length" ) |
Output:
Initial list of tuple [(11, 22, 33), (44, 55, 66)] All tuples have same length
Method #2: Using all()
# Python code to find whether all tuple # have equal length # Input list initilization Input = [( 11 , 22 , 33 ), ( 44 , 55 , 66 ), ( 11 , 23 )] k = 2 # Printing print ( "Initial list of tuple" , Input ) # Using all() Output = ( all ( len (elem) = = k for elem in Input )) # Checking whether all tuple # have equal length if Output: print ( "All tuples have same length" ) else : print ( "Tuples does not have same length" ) |
Output:
Initial list of tuple [(11, 22, 33), (44, 55, 66), (11, 23)] Tuples does not have same length
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.