Python Forum

Full Version: Replace for loop to search index position
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

I have following code which searches for index position of matching string without having to match everything:

sheet_num = []
for x in range(len(list_of_sheets)):
    if sheet_match in list_of_sheets[x]:
            sheet_num.append(x)
I'm looking for a better way to accomplish this as my code is filled with many occurrences of this type of for loop appending to an empty list.

I thought about:

list(map(lambda x: sheet_match in x, list_of_sheets))
But it returns a list of boolean values instead of the index position of the match. I'm sure its simple but I'm not so competent in Python to know it.

Thanks
Matt
Post working code sample that we can run,also you need to show what list_of_sheets and sheet_match is.
matching_sheet_indexes = [
    index for index, sheet in enumerate(list_of_sheets) if sheet_match in sheet
]
(Sep-03-2022, 11:37 AM)Yoriz Wrote: [ -> ]
matching_sheet_indexes = [
    index for index, sheet in enumerate(list_of_sheets) if sheet_match in sheet
]

Thank you! This did the trick. I was playing around with enumerate but couldn't get it to work as I'm not familiar with the 'index for index' part. Can I ask more about the code? What does this 'index for index' exactly do as the word 'index' is not called again? I suppose its iterating through the index of list_of_sheets but can you point me to something that clarify for a novice whats exactly happening here. Thanks
List comprehension. A shorthand way of writing a for loop that builds a list.
matching_sheet_indexes = []
for index, sheet in enumerate(list_of_sheets):
    if sheet_match in sheet:
        matching_sheet_indexes.append[index]
There are also dictionary, set and generator comprehensions.
(Sep-03-2022, 02:41 PM)deanhystad Wrote: [ -> ]List comprehension. A shorthand way of writing a for loop that builds a list.
matching_sheet_indexes = []
for index, sheet in enumerate(list_of_sheets):
    if sheet_match in sheet:
        matching_sheet_indexes.append[index]
There are also dictionary, set and generator comprehensions.

Thanks.