Can I search a list for a range of values?
Chris Angelico
rosuav at gmail.com
Fri Oct 14 18:20:33 EDT 2011
On Sat, Oct 15, 2011 at 9:10 AM, MrPink <tdsimpson at gmail.com> wrote:
> I have a list like so:
>
> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14]
>
> I would like to get a subset from the list with value between 10 and
> 20 (inclusive).
>
> b = [10,13,15,14,20]
>
> Is there a way to do this with a list or other data type?
Try a list comprehension:
>>> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14]
>>> [i for i in a if i>=10 if i<=20]
[10, 20, 15, 13, 14]
This preserves order from the original list. I don't know what order
your result list is in, but you can always rejig things after.
ChrisA
More information about the Python-list
mailing list