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
lst = ["b", "a", "bb"]
print([i for i in lst if i.startswith("b")][1])
Output:
"bb"
Or as a function:
def func(lst):
return [i for i in lst if i.startswith("b")][1]
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'
Try this :
def second_elemnt_starting_with_b(list_):
return [i for i in list_ if i.startswith('b')][1]
print(second_elemnt_starting_with_b(["b", "a", "bb"]))
Output :
'bb'
You can use the python built-in function startswith() to check the first element of the string.
lst = ["b", "a", "bb"]
# Check the first element
sample = "Sample"
print(sample.startswith("S"))
# Output : True
Now, you need to iterate through list to check each of the indices that starts with b
# Create empty list
lst_2 = []
# Loop through list
for element in lst.startswith("b"):
# Add every element starts with b
lst_2.append(element)
# Print the second element which starts with b
print(lst_2[1])