0

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!

  • 3
    The sub-expression `if d != first_name or first_letter` is not doing what you think. See https://stackoverflow.com/questions/20002503/why-does-a-x-or-y-or-z-always-evaluate-to-true – John Gordon Jul 13 '22 at 18:13
  • the expression `d != first_name or first_letter` is *always true*. – juanpa.arrivillaga Jul 13 '22 at 18:21
  • In any case, "I want to find the indexes of any names that are not "first_name" nor "first_letter"" is not really a clear requirement. Do you mean *that doesn't start with first_letter?* – juanpa.arrivillaga Jul 13 '22 at 18:22

3 Answers3

0

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)]
Khalil
  • 1,495
  • 6
  • 14
0
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]
Kavi Harjani
  • 661
  • 5
  • 15
0

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]]
fsimonjetz
  • 5,644
  • 3
  • 5
  • 21