0

I want to check the length of a list within a tuple, but I am having trouble doing this within a conditional statement.

If I have a tuple that looks like this:

ex_tuple = (['Hello', 'To', 'World'], ['Planet', 'Earth'], ['World', 'Of', 'Earth'])

I want to check if any of these lists in the tuple have > 2 elements.

Here's what I have (doesn't seem to be working):

if [(len(x)) for x in ex_tuple > 2]:
... do rest of program

But, I get an error message that '>' is not supported between tuple and ints. I've also tried using '!= 1 or 2', but I get a similar message.

This seems like a simple fix, but I am having trouble figuring out where I am going wrong. Would appreciate any help - thanks!

2 Answers2

3

The built-in function any() takes a list and evaluates True if any elements are True, and False if they're all false. Put your list comprehension in there, and move your conditional > 2 over next to len(x) and drop the parentheses around it

any(len(x)>2 for x in ex_tuple)
True
Waket Zheng
  • 5,065
  • 2
  • 17
  • 30
Joe Carboni
  • 421
  • 1
  • 6
0

Hi you can try this simple loop to check it;

for word_list in ex_tuple:
    if len(list) > 2:
        print(f"{list}: has more than 2 items.")

Result:

['Hello', 'To', 'World']: has more than 2 items.
['World', 'Of', 'Earth']: has more than 2 items.
Lanre
  • 340
  • 2
  • 6