Home > Net >  Finding index numbers in a Python list?
Finding index numbers in a Python list?

Time:07-14

If I have a list like this:

name_lst = ['Karen', 'Katrina', 'Karen', 'Kareem', 'F']

Where:

first_name = "Karen"
first_letter = "F"

I want to find the indexes of any names that are not "first_name" nor "first_letter". So, I want my output to look like this:

print(output)
#[1, 2]

So far, my code looks like this, which doesn't quite work:

index_name = [i for i, d in enumerate(name_lst) if d != first_name or first_letter]
print(index_name)

I feel like this is a simple fix, but I'm not able to figure out where I'm going wrong. Would appreciate any help - thanks!

CodePudding user response:

You can check if the name starts with first_letter using the startswith string method. Also you need to and the result of both conditions.

index_name = [i for i, d in enumerate(name_lst) if d != first_name and ! d.startswith(first_letter)]

CodePudding user response:

name_lst = ['Karen', 'Katrina', 'Karen', 'Kareem', 'F']
first_name = "Karen"
first_letter = "F"
index_name = [i for i, d in enumerate(name_lst) if d != first_name and d != first_letter]
print(index_name)

output

[1, 3]

CodePudding user response:

Don't chain multiple (un)equal checks - use a list of elements to exclude instead.

index_name = [i for i, d in enumerate(name_lst) if d not in [first_name, first_letter]]
  • Related