
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Test if Tuple List Has a Single Element in Python
When it is required to test if a tuple list contains a single element, a flag value and a simple iteration is used.
Example
Below is a demonstration of the same
my_list = [(72, 72, 72), (72, 72), (72, 72)] print("The list is :") print(my_list) my_result = True for sub in my_list: flag = True for element in sub: if element != my_list[0][0]: flag = False break if not flag: my_result = False break if(flag == True): print("The tuple contains a single element") else: print("The tuple doesn't contain a single element")
Output
The list is : [(72, 72, 72), (72, 72), (72, 72)] The tuple contains a single element
Explanation
A list of list is defined and is displayed on the console.
A variable is assigned to ‘True’.
The list is iterated over, and a value is flagged as ‘True’.
If an element of the list is not equal to the first element of the list, the value is flagged to ‘False’.
Otherwise, the variable is changed to ‘False.
The control is broken outpf the loop.
Outside the method, if the flagged value is ‘True’, it means the list contains a single element only.
Relevant message is displayed on the console.
Advertisements