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:



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
Python: Tips of the Day
Get Current Process Id:
import os os.getpid()
21423
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook