Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Test if tuple list has a single element
When it is required to test if a tuple list contains a single unique element across all tuples, we can use different approaches. This means checking if all elements in all tuples are the same value.
Using Nested Loop with Flag
The traditional approach uses nested loops with a flag variable to track whether all elements are identical ?
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 my_result == True:
print("The tuple list contains a single unique element")
else:
print("The tuple list doesn't contain a single unique element")
The list is : [(72, 72, 72), (72, 72), (72, 72)] The tuple list contains a single unique element
Using Set and Chain
A more concise approach flattens all tuples and checks if the set has only one unique element ?
from itertools import chain
tuple_list = [(72, 72, 72), (72, 72), (72, 72)]
print("The list is :")
print(tuple_list)
# Flatten all tuples and convert to set
all_elements = set(chain(*tuple_list))
has_single_element = len(all_elements) == 1
if has_single_element:
print("The tuple list contains a single unique element")
else:
print("The tuple list doesn't contain a single unique element")
The list is : [(72, 72, 72), (72, 72), (72, 72)] The tuple list contains a single unique element
Using all() Function
The most Pythonic approach uses the all() function to check if all elements equal the first element ?
tuple_list = [(5, 5), (5, 5, 5), (5,)]
print("The list is :")
print(tuple_list)
# Get the first element as reference
first_element = tuple_list[0][0]
# Check if all elements in all tuples equal the first element
has_single_element = all(
element == first_element
for sub_tuple in tuple_list
for element in sub_tuple
)
if has_single_element:
print("The tuple list contains a single unique element")
else:
print("The tuple list doesn't contain a single unique element")
The list is : [(5, 5), (5, 5, 5), (5,)] The tuple list contains a single unique element
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Nested Loop | Moderate | Good (early exit) | Learning purposes |
| Set + Chain | Good | Moderate | Small datasets |
| all() Function | Excellent | Good (early exit) | Production code |
Conclusion
Use all() with generator expression for the most readable and efficient solution. The set approach is good for understanding unique elements, while nested loops provide explicit control over the checking process.
