1
my_list = [[1,2],[1,3],[1,3],[1,3]]
my_var = 7

My goal is to be able to see if my_var is larger than all of the positions at my_list[0][1] and my_list[1][1] and my_list[2][1] and so on.

my_list can vary in length and my_var can also vary so I am thinking a loop is the best bet?

*very new to python

2 Answers 2

4
all(variable > element for element in list)

or for element i of lists within a list

all(variable > sublist[i] for sublist in list)

This has the advantage of kicking out early if any of the elements is too large. This works because the ... for ... in list is an instance of Python's powerful and multifarious generator expressions. They are similar to list comprehensions but only generate values as needed.

all itself just checks to see if all of the values in the iterable it's passed are true. Generator expressions, list comprehensions, lists, tuples, and other sorts of sequences are all iterables.

So the first statement ends up being equivalent to calling a function like

def all_are_greater_than_value(list, value):
    for element in list:
        if element <= value:
            return False
    return True

with all_are_greater_than_value(list, variable)...

or simply

all_greater = True
for element in list:
    if element <= value:
        all_greater = False
        break

However, the generator expression is generally preferred, being more concise and "idiomatic".

Sign up to request clarification or add additional context in comments.

3 Comments

It's a great example of Python's ability to read like English.
this may make you cringe but would you mind showing me how this could be done using a primitive for loop?
@Dtour: I added some for-loop examples for comparison.
1

You can do it like this also:

my_list = [[1,2],[1,3],[1,3],[1,3]]
my_var = 7
print all(all(x < my_var for x in sublist) for sublist in my_list)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.