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

3
  • If you need only first occurrence, just loop through l and return element when you find it. def f(l, sub): for x in l: if sub in x: return x Commented Nov 28, 2019 at 14:08
  • What about: next(filter(lambda x: sub in x, l)) Commented Nov 28, 2019 at 14:08
  • next((x for x in l if sub in x), None) Commented Nov 28, 2019 at 14:15

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

4

Very simple:

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

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.