2

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'?

Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48

3 Answers3

8

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)
UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
4

Very simple:

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

In this way you don't create the entire list.

Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
0
next(x for x in iter(l) if sub in x)
Raymond Reddington
  • 1,709
  • 1
  • 13
  • 21