Wednesday, January 22, 2025
HomeProgrammingWhat are Python List index()?

What are Python List index()?

In Python, the index() method is used to find the first occurrence of a specified value in a list. It returns the index of the value if found, otherwise it raises a ValueError if the value is not present.

Syntax:
python
list.index(element, start, end)

See also  What is Abstract Class in Java

– element: The value to search for.
– start (optional): The position to start the search.
– end (optional): The position to end the search.

Example:
python
numbers = [10, 20, 30, 40, 50]
index = numbers.index(30)
print(index) # Output: 2

Handling ValueError:
To avoid ValueError, you can use a conditional check:
python
if 60 in numbers:
print(numbers.index(60))
else:
print(“Value not found”)

See also  PowerShell Run as Administrator

The index() method is useful for locating the position of an element in a list, especially when dealing with lists containing unique values or needing to know the first occurrence.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x