Python – Test if tuple list has a single element

When it is required to test if a tuple list contains a single element, a flag value and a simple iteration is used.


Below is a demonstration of the same

my_list = [(72, 72, 72), (72, 72), (72, 72)]

print("The list is :")

my_result = True
for sub in my_list:
   flag = True
   for element in sub:
      if element != my_list[0][0]:
         flag = False
   if not flag:
      my_result = False

if(flag == True):
   print("The tuple contains a single element")
   print("The tuple doesn't contain a single element")


The list is :
[(72, 72, 72), (72, 72), (72, 72)]
The tuple contains a single element


  • 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.