Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequence find function in Python

How do I find an object in a sequence satisfying a particular criterion?

List comprehension and filter go through the entire list. Is the only alternative a handmade loop?

mylist = [10, 2, 20, 5, 50] find(mylist, lambda x:x>10) # Returns 20 
like image 635
Salil Avatar asked May 18 '11 03:05

Salil


People also ask

Is there a sequence function in Python?

Python supports six different types of sequences. These are strings, lists, tuples, byte sequences, byte arrays, and range objects. We will discuss each of them.

What is seq () in Python?

In Python, sequence is the generic term for an ordered set. There are several types of sequences in Python, the following three are the most important. Lists are the most versatile sequence type. The elements of a list can be any object, and lists are mutable - they can be changed.

Is set a sequence in Python?

Sets aren't sequences - they have no order and they can't be indexed via set[index] - they even don't have any kind of notion of indices. (They are iterable , though - you can iterate over their items.)


2 Answers

Here's the pattern I use:

mylist = [10, 2, 20, 5, 50] found = next(i for i in mylist if predicate(i)) 

Or, in Python 2.4/2.5, next() is a not a builtin:

found = (i for i in mylist if predicate(i)).next() 

Do note that next() raises StopIteration if no element was found. In most cases, that's probably good. You asked for the first element, no such element exists, and so the program probably cannot continue.

If, on the other hand, you do know what to do in that case, you can supply a default to next():

conf_files = ['~/.foorc', '/etc/foorc'] conf_file = next((f for f in conf_files if os.path.exists(f)),                  '/usr/lib/share/foo.defaults') 
like image 165
SingleNegationElimination Avatar answered Oct 16 '22 04:10

SingleNegationElimination


Actually, in Python 3, at least, filter doesn't go through the entire list.

To double check:

def test_it(x):     print(x)     return x>10  var = next(filter(test_it, range(20))) 

In Python 3.2, that prints out 0-11, and assigns var to 11.

In 2.x versions of Python you may need to use itertools.ifilter.

like image 34
Jeremiah Avatar answered Oct 16 '22 05:10

Jeremiah