1

I'm trying to get the indices of all the elements which match a certain condition in my_list.

my_list = ['This is chapter 1', 'chapter 2 is here', 'Baseball Sport', 'Football Sport', 'chapter 13']

I want to get all the indices of the elements in my_list which contain the string 'chapter'. I've tried list comprehensions but I'm still new so ain't getting successful.

search = 'Chapter'

for k in range(len(my_list)):
    search_list = [i for i, search in enumerate(my_list)
                   if search.lower() in my_list[k]]

I'm probably doing some mistake here which can't yet identify. How can I get my desired result of indices?

search_list = [0, 1, 4]
Georgy
  • 12,464
  • 7
  • 65
  • 73
pythonc229
  • 45
  • 1
  • 4

5 Answers5

2

The main problem is that you are redefining search within the list-comprehension and the new definition of it is being used. What you want is this:

my_list = ['This is chapter 1', 'chapter 2 is here', 'Baseball Sport', 'Football Sport', 'chapter 13']
search = 'chapter'
results = [i for i, item in enumerate(my_list) if search in item]

Sidenotes:

  1. If you have the power to define search yourself, there is no point defining it as "Chapter" and call .lower() on it every time. Define it as "chapter" instead from the get go.
  2. A list comprehension replaces an explicit for loop. Having both is in this case a mistake. You only need to loop once over the list.
  3. enumerate is used in order to avoid indexing (my_list[k]). You are correct to use enumerate here; so use it.
Ma0
  • 15,057
  • 4
  • 35
  • 65
  • Thank you for the detailed answer. As for the search I used it as an example here. I'm scrapping data from a webpage so I build the list in lower case and also use search in lower case to match results. – pythonc229 May 26 '20 at 08:58
2

You can do this

my_list = ['This is chapter 1', 'chapter 2 is here', 'Baseball Sport', 'Football Sport', 'chapter 13']

search = "chapter"

search_list = [index for index, val in enumerate(my_list) if search in val]

This gives the output as

[0, 1, 4]

which is your desired output IMHO. I hope it helps :)

1

You can do this:

my_list = ['This is chapter 1', 'chapter 2 is here', 'Baseball Sport', 'Football Sport', 'chapter 13']

search = 'Chapter'
search_list = []
for i, k in enumerate(my_list):
  if search.lower() in k:
    search_list.append(i)
print(search_list)
0

I would do it like this:

my_list = ['This is chapter 1', 'chapter 2 is here', 'Baseball Sport', 'Football Sport', 'chapter 13'] 

search = 'Chapter'

search_list = [i for i, str_to_search in enumerate(my_list) if search.lower() in str_to_search]

noteness
  • 2,440
  • 1
  • 15
  • 15
0

Is best way to solve your problem :):

search_list = [i for i, str_to_search in enumerate(my_list) if 'chapter' in 
str_to_search]