If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:
next(obj for obj in objs if obj.val == 5)
This is however faster than a complete list comprehension. Compare these two:
[i for i in xrange(100000) if i == 1000][0]
next(i for i in xrange(100000) if i == 1000)
The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).
Answer from eumiro on Stack OverflowIf you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:
next(obj for obj in objs if obj.val == 5)
This is however faster than a complete list comprehension. Compare these two:
[i for i in xrange(100000) if i == 1000][0]
next(i for i in xrange(100000) if i == 1000)
The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).
This will return the object if found, else it will return "not found"
a = [100, 200, 300, 400, 500]
def search(b):
try:
k = a.index(b)
return a[k]
except ValueError:
return 'not found'
print(search(500))
python - Find first element in a sequence that matches a predicate - Stack Overflow
Help finding first instance of a element in tuple/list
Help operating in a smart way to make lists of first element in lists of list.
How to get first empty string in a list in Python
To find the first element in a sequence seq that matches a predicate:
next(x for x in seq if predicate(x))
Or simply:
Python 2:
next(itertools.ifilter(predicate, seq))
Python 3:
next(filter(predicate, seq))
These will raise a StopIteration exception if the predicate does not match for any element.
To return None if there is no such element:
next((x for x in seq if predicate(x)), None)
Or:
next(filter(predicate, seq), None)
You could use a generator expression with a default value and then next it:
next((x for x in seq if predicate(x)), None)
Although for this one-liner you need to be using Python >= 2.6.
This rather popular article further discusses this issue: Cleanest Python find-in-list function?.
Hello everyone, I'm currently working with graphs on python and I'm trying to implement a program for school where I can find all the roads to certain nodes and print the node found first. I'm stuck on this last part specifically. After doing my function I finally get my roadmap as such:
([[5], [4, 5], [4], [3, 4], [3], [1, 3], [1], [3, 7], [7], [1, 7], [1, 8], [8], [2, 7], [2], [2, 6], [6]],)
Where I was looking for the roads starting from 5 to 6,7 and 8. As you can see here I found [7] first.
My question is : how do I print only the first value found out of a list of 3 or more numbers? In this case in particular it would be 7 (notice I only want the instance where 7 is alone, not [3,7] or [1,7]
I already tried:
item for item in tuple if item==7 or item==8 or item==9
to no avail
Thank you!