w3resource

Python List: index() Method

index() Method

The index method() is used to get the zero-based index in the list of the first item whose value is given.

Visual Explanation:

Python List: index() method
Python List: index() method
Python List: index() method

Syntax:

list.index(element, start, end)

Parameters:

  • element - The element to be searched.
  • start (optional), end (optional) - 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.

Return Value from List index()

  • Return zero-based index in the list of the first item
  • Raises a Value Error if there is no such item.

Example 1: Find the index of an element in a list


# colors list
colors = ['Red', 'Green', 'Black', 'Green']
print("Original list:") 
print(colors)  
print("Position at the first occurrence of the specified value:")
p = colors.index("Green")
print(p)

Output:

Original list:
['Red', 'Green', 'Black', 'Green']
Position at the first occurrence of the specified value:
1

Example 2: Find index of an element after a given position in a list


# fruits list
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
print("Original list:") 
print(fruits)  
print("\nPosition of 'apple' after the specified position:")
p = fruits.index("apple", 4)
print(p)

Output:

Original list:
['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

Position of 'apple' after the specified position:
5

Example 3: Find index of an element within a certain range in a list


# fruits list
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
print("Original list:") 
print(fruits)  
print("\nPosition of 'apple' within a certain range:")
p = fruits.index("apple", 2, 6)
print(p)

# print("\nPosition of 'apple' within a certain range:")
# p = fruits.index("apple", 2, 3)
# print(p)
# Will raise ValueError: 'apple' is not in list

Output:

Original list:
['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

Position of 'apple' within a certain range:
5

Python Code Editor:

Previous:Python List extend() Method
Next: Python List insert() Method

Test your Python skills with w3resource's quiz



Follow us on Facebook and Twitter for latest update.