C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python List index() MethodPython index() method returns index of the passed element. This method takes an argument and returns index of it. If the element is not present, it raises a ValueError. If list contains duplicate elements, it returns index of first occurred element. This method takes two more optional parameters start and end which are used to search index within a limit. Signatureindex(x[, start[, end]]) ParametersNo parameter ReturnIt returns None. Let's see some examples of index() method to understand it's functionality. Python List index() Method Example 1Let's first see a simple example to get index of an element using index() method. # Python list index() Method # Creating a list apple = ['a','p','p','l','e'] # Method calling index = apple.index('p') # Displaying result print("Index of p :",index) Output: Index of p : 1 Python List index() Method Example 2The method returns index of first element occurred, if the element is duplicate. See the following example. # Python list index() Method # Creating a list apple = ['a','p','p','l','e'] # Method calling index = apple.index('l') # 3 index2 = apple.index('p') # always 1 # Displaying result print("Index of l :",index) print("Index of p :",index2) Output: Index of l : 3 Index of p : 1 Python List index() Method Example 3The index() method throws an error ValueError if the element is not present in the list. See the example below. # Python list index() Method # Creating a list apple = ['a','p','p','l','e'] # Method calling index = apple.index('z') # Displaying result print("Index of l :",index) Output: index = apple.index('z') ValueError: 'z' is not in list Python List index() Method Example 4Apart from element, the method takes two more optional parameters start and end. These are used to find index within a limit. # Python list index() Method # Creating a list apple = ['a','p','p','l','e'] # Method calling index = apple.index('p',2) # start index index2 = apple.index('a',0,3) # end index # Displaying result print("Index of p :",index) print("Index of a :",index2) Output: Index of p : 2 Index of a : 0
Next TopicPython Lists
|