Search code examples
pythonloopsnested-loops

Python: Append value to new list if it starts with an specific letter and then go to next list and append those values


I am trying to understand how to iterate through two lists look for words that begin with a specific letter and append them to a new list. I was thinking of using for loop and a nested for loop but my code is not working.

list1 = ['iPad','iPhone','macbook','screen','bottel cap','paper','keyboard', 'mouse','bat','Baseball']

list2 = ['couch','tv','remote control', 'play station', 'chair', 'blanket', 'table', 'mug']

list_letter_b = []

for item in list1:
    if item[0] == "b":
        list_letter_b.append(item)
for item in list2:
    if item[0] == "b":
        list_letter_b.append(item)
print("Here is your new list with only items starting with letter b or B {} ".format(list_letter_b))

This code works but it seems too long there has to be a way of making it simpler. Also, I would love to take values that are b and B but cant seems to make it happen.

Any advice is greatly appreciated.

Thank you


Solution

  • Since u also want the values that have an uppercase 'B', you can call .lower() function on the item in the if condition if item[0].lower() == "b":

    list1 = ['iPad','iPhone','macbook','screen','bottel cap','paper','keyboard', 'mouse','bat','Baseball']
    
    list2 = ['couch','tv','remote control', 'play station', 'chair', 'blanket', 'table', 'mug']
    
    list_letter_b = []
    
    for item in list1 + list2:
        if item[0].lower() == "b":
            list_letter_b.append(item)
    
    print("Here is your new list with only items starting with letter b or B {} ".format(list_letter_b))