Finding the first index in a list greater than a particular value

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Mon Aug 15 01:57:57 EDT 2016


Atri Mahapatra writes:

> I have a list of dictionaries which look like this:
> [{'Width': 100, 'Length': 20.0, 'Object': 'Object1'}, {'Width': 12.0, 'Length': 40.0, 'Object': 'Object2'}...... so on till 10] 
>
> I would like to find the first index in the list of dictionaries whose
> length is greater than a particular value
>
> f=lambda seq, m: [ii for ii in range(0, len(seq)) if seq[ii]['Length'] > m][0] and it throws an error

It doesn't throw an error (raise an exception) if there is at least one
such dictionary in the list.

If you see an error message for some other reason, you need to give more
information. Like, what error? And for what code exactly. This problem
can probably be tested with [{'Length':20.0}, {'Length':40.0}], so you
don't need much code to ask the question.

(Some people avoid giving actual details at a great cost. Even when
asked nicely. Repeatedly. Such people cannot be helped. A mystery.)

> can  anyone suggest a way  to do it?

Use a generator expression instead of a list comprehension. Ask for the
next value from the generator object, or a default when there is no next
value.

next((k for k,d in enumerate(ll) if d['Length'] > 23), 'sorry')
==> 1

next((k for k,d in enumerate(ll) if d['Length'] > 43), 'sorry')
==> 'sorry'

It's often better to iterate over enumerate(ll) to get both the index
and the value than over range(len(ll)) to get only the index.

Or just write an actual elementary for-loop that returns the index when
it finds the first good value:

def f(dictses, tooshort):
   for k,d in enumerate(dictses):
       if d['Length'] > tooshort:
           return k
   return 'sorry'

The default value from a function is None (if it falls through without a
return statement). There is a tradition of returning -1 when no valid
index is found. The one thing not to do is to use a non-index as if it
was a valid index. An exception in an exceptional situation may be a
good thing precisely because it calls attention to itself.



More information about the Python-list mailing list