Tomasz Hołda
Tomasz Hołda

Reputation: 113

Get string from list if that string contains substring

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

Answers (3)

Raymond Reddington
Raymond Reddington

Reputation: 1837

next(x for x in iter(l) if sub in x)

Upvotes: 0

UltraInstinct
UltraInstinct

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

Riccardo Bucco
Riccardo Bucco

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

Related Questions