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



Share this Tutorial / Exercise on : Facebook and Twitter

Python: Tips of the Day

Inserting if statements using conditional list comprehensions:

x = [1, 2, 3, 4, 5, 6]
result = []
for idx in range(len(x)):
    if x[idx] % 2 == 0:
        result.append(x[idx] * 2)
    else:
        result.append(x[idx])
result

Output:

[1, 4, 3, 8, 5, 12]
[(element * 2 if element % 2 == 0 else element) for element in x]

Output:

[1, 4, 3, 8, 5, 12]
[element * 2 for element in x if element % 2 == 0]

Output:

[4, 8, 12]