How Can I Return The Second Element In The List That Starts With "b"
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_elemnt_starting_with_b(['b', '
Solution 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.
defsecond_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 onereturnnext(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
defnth_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'))
    returnnext(islice(g, n-1, n))
nth_element_starting_with_b(["b", "a", "bb"], 2) 
# 'bb'Solution 2:
Try this :
defsecond_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'Solution 3:
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]
Solution 4:
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 : TrueNow, you need to iterate through list to check each of the indices that starts with b
# Create empty list
lst_2 = []
# Loop through listfor element in lst.startswith("b"):
    # Add every element starts with b
    lst_2.append(element)
    # Print the second element which starts with bprint(lst_2[1])
Post a Comment for "How Can I Return The Second Element In The List That Starts With "b""