Reputation: 113
Lets say I have following data:
l = ['abc', 'def', 'ghi']
sub = 'bc'
'bc' will allways be a substring for only one element in the list!
and a function that works like this:
def f(l, sub):
return [x for x in l if sub in x][0]
So the function will return 'abc' because it has 'bc' in it
My Question is: What is the other way to write that function so it doesn't use list index? ([0]) Is there a way to do this any 'prettier'?
Upvotes: 2
Views: 1670
Reputation: 44424
Use next(..)
with a generator. This will sort of break
the moment it finds the first instance. Of course, this is assuming one element definitely exists in your list.
def f(l, sub):
return next(x for x in l if sub in x)
Upvotes: 8
Reputation: 15364
Very simple:
next(x for x in l if sub in x)
In this way you don't create the entire list.
Upvotes: 4