Jack Smith
Jack Smith

Reputation: 31

Searching for a letter within a list

I'm very new to coding and am taking an online course at the moment. Using the CodeHS sandbox to make programs and having a bit of a hard time with this one. I am trying to make my program look through this list of names and return which ones have the letter "E" / "e" in them. I also want it to keep count of how many names are being found and eventually return that count. Any help appreciated, thanks in advance. Here is my code so far:

middle_names = ["Michael", "Abdallah", "Parvati", "Sanskriti", "Piper", "Samuel", "Lee", "Meg", "Michael", "Mohamed", "Sofia", "Ahmed Hani", "Josh", "Lawrence", "Mireya", "Mingyue", "Bradley Theodore", "McKenna", "Ali"]


def search():
    if "e" in middle_names:
        print middle_names

search()

Upvotes: 1

Views: 135

Answers (3)

Sushant
Sushant

Reputation: 3669

Use python's sweet list comprehension, which will return you a list containing all the names that have "e" in them like -

middle_name_contains_e = [i for i in middle_names if 'e' in i]

and as pointed out in the comment, just replace 'e' with 'E' to match capital letter like so -

middle_name_contains_e = [i for i in middle_names if 'E' in i]

Or you could manually loop through all the names in the list like so -

def middle_name_contains_e():
    names = []
    for name in middle_names:
        if "e" in name:
            names.append(name)
    return names
names = middle_name_contains_e()

Upvotes: 2

jpp
jpp

Reputation: 164793

Loop approaches

You need to cycle through each item in your list. This is commonly achieved via a for loop:

def search(lst, k):
    for item in lst:
        if 'e' in item:
            print(item)

search(middle_names, 'e')

A couple of ways you can improve such an algorithm is to account for lower or upper case letters, e.g. via str.casefold, and use return or yield statements to have the function give an output. Here's an example using a generator:

def search(lst, k):
    for item in lst:
        if 'e' in item.casefold():
            yield item

for res in search(middle_names, 'e'):
    print(res)

Comprehensions

One Pythonic and efficient approach is to use a list comprehension:

res = [item for item in middle_names if 'e' in item.casefold()]
print(res)

Or, if you want a lazy approach, you can use a generator comprehension:

res = (item for item in middle_names if 'e' in item.casefold())
print(*res, sep='\n')

Upvotes: 0

YOLO
YOLO

Reputation: 21749

You could also do this to calculate count & letters with e in one function:

def search(x):
    e_list = []
    for i in x:
        if 'e' in i:
            e_list.append(i)
    return len(e_list), e_list

count,e_list = search(middle_names)
# count = 13
# e_list = ['Michael', 'Piper', 'Samuel', 'Lee', 'Meg', 'Michael', 'Mohamed', 'Ahmed Hani', 'Lawrence', 'Mireya', 'Mingyue', 'Bradley Theodore', 'McKenna']

Upvotes: 0

Related Questions