Introduction

Lists are useful in different ways compared to other datatypes because of how versatile they are. In this article we’ll take a look at one of the most common operations with lists - finding the index of an element.

We will take a look at different scenarios of finding an element, i.e. finding the first, last, and all occurrences of an element. As well as what happens when the element we’re looking for doesn’t exist.

Using the index() Function

All of the operations we mentioned in the last paragraph can be done with the built-in index() function. The syntax for this function is index(element[, start[, end]]).

The element parameter naturally represents the element we’re looking for. The start and end parameters are optional and represent the range of indices in which we look for the element.

The default value for start is 0 (searching from the beginning), and the default value for end is the number of elements in the list (searching to the end of the list).

The function returns the first position of the element in the list that it could find, regardless of how many equal elements there are after the first occurrence.

#python #index

Python: Check Index of an Item in a List
35.70 GEEK