Reputation: 326
I am attempting to see if an integer at a given location is greater than every other integer within that list. For example:
values = [2,5,3,1,6]
if values[0] < all other integers
print something
Keep in mind, I need to see if that specific index is less than all of the other indexes in the list, therefore, using something like min(values)
will not work. A list such as
values = [2,5,3,1,6,1]
has no single minimum value; any given index should return False
.
Upvotes: 0
Views: 68
Reputation: 103844
You can use any to assert if any one item in the list meets a condition. Just skip the one entry in question like so:
def f(li, idx):
return any(e>li[idx] for i, e in enumerate(li) if i!=idx)
>>> f([2,5,3,1,6], 0)
True
>>> f([2,5,3,1,6], 4)
False
You can reverse <
to >
or whatever to fit your use. (Or add a not
)
If you want to assert that the given index has a relationship with all other list elements, use all:
def f2(li, idx):
return all(e>li[idx] for i, e in enumerate(li) if i!=idx)
>>> f2([2,5,3,1,6,1], 3)
False
Upvotes: 3
Reputation: 123463
You could use the built-in any()
function like this:
values = [2,5,3,1,6]
loc = 4
if not any((values[i] > values[loc]) for i in range(len(values)) if i != loc):
print('something')
Upvotes: 1
Reputation: 77847
Use the all
operator to iterate over a sequence. In this case, you also have to eliminate checking against self. The boolean expression would be:
>>> values = [2,5,3,1,6]
>>> given_loc = 0
>>> all ([values[given_loc] < values[i] \
for i in range(len(values)) \
if i != given_loc])
False
>>> given_loc = 3
>>> all ([values[given_loc] < values[i] for i in range(len(values)) if i != given_loc])
True
Upvotes: 1