views:

84

answers:

2

reworked to hopefully make it clearer.

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

+3  A: 
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".

intuited
+1. I didn't even think about that
aaronasterling
That's pretty cool. Thanks!
Dtour
It's a great example of Python's ability to read like English.
intuited
this may make you cringe but would you mind showing me how this could be done using a primitive for loop?
Dtour
@Dtour: I added some for-loop examples for comparison.
intuited
many thanks. I am definitely starting to see the power.
Dtour
A: 

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)
Tony Veijalainen