If the same element is present more than once, the method returns the index … This provides us with the index of each item in our colors list, which is the same way that C-style for loops work. The index () method returns the position at the first occurrence of the specified value. Python | Accessing index and value in list There are various methods to access the elements of a list, but sometimes we may require to access element along with the index on which it is found. Method #1 : Naive method Python List index () The index () method searches an element in the list and returns its index. Parameters. list.index(x[, start[, end]]) Return zero-based index in the list of the first item whose value is equal to x . Python. To get the actual color, we use colors [i]. We can loop over this range using Python’s for-in loop (really a foreach).
In simple terms, the index () method finds the given element in a list and returns its position. # List of strings listOfElems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok'] # Get indexes of all occurrences of 'Ok' in the list indexPosList = getIndexPositions (listOfElems, 'Ok') print ('Indexes of all occurrences of "Ok" in the list are : ', indexPosList) 1. Raises a ValueError if there is no such item. for-in: the usual way Return Value. Example. Syntax. The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. Let’s see all the different way of accessing both index and value in a list. Python List index () Method Description. Python list method index () returns the lowest index in list that obj appears. 2.