6

I have a list

myList = ["what is your name", "Hi, how are you", "What about you", "How about a coffee", "How are you"] 

Now I want to search index of all occurrence of "How" and "what". How can I do this in Pythonic way?

1
  • What if How or what appears more than once in a string? And what about case sensitivity? Commented Jun 9, 2015 at 10:44

2 Answers 2

5

Sounds like a one-liner Python is able to do!

[i for i, j in enumerate(myList) if 'how' in j.lower() or 'what' in j.lower()] 
Sign up to request clarification or add additional context in comments.

2 Comments

Has anyone really tried this one? It should be j.lower(), i is the index, right?
@lord63.j Yup, my bad. Forgot to change it when I first changed [j for ... to [i for ...
1

This will work, but assumes you do not care about case sensitivity:

myList = ["what is your name","Hi, how are you","What about you","How about a coffee","How are you"] duplicate = "how are you" index_list_of_duplicate = [i for i,j in enumerate(myList) if duplicate in j.lower()] print index_list_of_duplicate [1,4] 

4 Comments

He wanted indexes, so it should be [j for i, j...] ;)
no, j is the entry of the list, i is the number from enumerate
Oops, silly me. This is what happens when you haven't been around python for ages
Pfiew. I think I went crazy for a second :P