Skip to content

Instantly share code, notes, and snippets.

@imedadel
Created November 3, 2019 09:10
Show Gist options
  • Select an option

  • Save imedadel/b48f9274033603e4c9b50da09a2bb6ac to your computer and use it in GitHub Desktop.

Select an option

Save imedadel/b48f9274033603e4c9b50da09a2bb6ac to your computer and use it in GitHub Desktop.
Finding the first occurrence of an item in a filtered Python list

Finding the first occurrence

If you only want the first thing that matches a condition (but you don't know what it is yet), it's fine to use a for loop (possibly using the else clause as well, which is not really well-known). You can also use

next(x for x in lst if ...)

which will return the first match or raise a StopIteration if none is found. Alternatively, you can use

next((x for x in lst if ...), [default value])

Source: https://stackoverflow.com/a/9542768/3737308

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment