search
Search
Publish
menu
menu search toc more_vert
Robocat
Guest 0reps
Thanks for the thanks!
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
help Ask a question
Share on Twitter
search
keyboard_voice
close
Searching Tips
Search for a recipe: "Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to
A
A
share
thumb_up_alt
bookmark
arrow_backShare
Twitter
Facebook

Python List | index method

Programming
chevron_right
Python
chevron_right
Operations
chevron_right
List Operations
chevron_right
Documentation
schedule Mar 10, 2022
Last updated
local_offer Python
Tags

Python's list.index(~) method returns the position of the first occurrence of the specified element in a list.

Parameters

1. x | any

The element to search for in the list.

2. start | number | optional

The index position from which to start the search (inclusive). Defaults to 0.

3. end | number | optional

The index position at which to end the search (exclusive). Defaults to length of list (i.e. last index position in list + 1).

Return value

Index position of the first occurrence of the element x in the list.

Examples

Basic usage

To return the index position of the first occurrence of 'koala' in animals list:

animals = ['koala', 'rabbit', 'dog', 'cat', 'koala']
animals.index('koala')
0

Note that index positions in Python start at 0 not 1. Therefore we see return value of 0 as 'koala' is the first element in list animals.

ValueError

To return the index position of the first occurrence of 'panda' in animals list:

animals = ['koala', 'rabbit', 'dog', 'cat', 'koala']
animals.index('panda')
ValueError: 'panda' is not in list

As 'panda' does not exist in the list animals, a ValueError is raised:

Start parameter

To start the search for 'koala' at index position 1 of animals:

animals = ['koala', 'rabbit', 'dog', 'cat', 'koala']
animals.index('koala', 1)
4

4 is returned as 'koala' first occurs at index position 4 (5th element) after index position 1 in animals.

End parameter

To end the search for 'cat' at the third to last element in animals:

animals = ['koala', 'rabbit', 'dog', 'cat', 'koala']
animals.index('cat', 0, -2)
ValueError: 'cat' is not in list

The search excludes the element at index position end (in this case -2 (second to last element) which is occupied by element 'cat'). As a result the search ends after checking element at index position -3 ('dog'), which is why a ValueError is thrown.

robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Ask a question or leave a feedback...