Friday, January 17, 2020

Python - Return the indexes of all occurrences of a string in a list

Here is the function to return the indexes of a certain string occurrences in a list:

def getIndexPositions(listOfString, certainString):
    ''' Returns the indexes of all occurrences of give element in    
        the list- listOfString'''

    indexList = []
    indexPos = 0    
    while True:
        try:
            # Search for item in list from indexPos to the end of list            
            indexPos = listOfString.index(certainString, indexPos)
            # Add the index position in list            
            indexList.append(indexPos)
            indexPos += 1        
        except ValueError as e:
            break
    return indexList

No comments:

Post a Comment