I have this function with lists that has strings in it and I have to find the second element in this list that starts with \"b\".
for example:
second_e
It would be more efficient to use a generator, rather than build lists of all strings starting with 'b' by iterating over the whole initial list, then only keep the second one.
def second_element_starting_with_b(lst):
# g is a generator, it will produce items lazily when we call 'next' on it
g = (item for item in lst if item.startswith('b'))
next(g) # skip the first one
return next(g)
second_element_starting_with_b(["b", "a", "bb"])
# 'bb'
This way, the code stops iterating on the initial list as soon as the string we are looking for is found.
As suggested by @Chris_Rands, it is also possible to avoid repeated calls to next by using itertools.islice. This way, an extended version looking for the nth item starting with 'b' would look like:
from itertools import islice
def nth_element_starting_with_b(lst, n):
"Return nth item of lst starting with 'b', n=1 for first item"
g = (item for item in lst if item.startswith('b'))
return next(islice(g, n-1, n))
nth_element_starting_with_b(["b", "a", "bb"], 2)
# 'bb'