TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: List Index Method in Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

List Index Method in Python

Last updated: Oct 29, 2023 5:07 pm
By Meenakshi Agarwal
Share
2 Min Read
Python List Index Method Explained with Examples
Python List Index Method Explained with Examples
SHARE

This guide will teach you how to find the index of an element in a Python list. You will learn how to use the list.index() method with practical examples.

Contents
List Index MethodHow does the Python list Index() function work?Program ExamplesUsing the wrong elementFind the element index in a tupleKey Facts

Please note that the code examples provided below follow Python 3 syntax. You can adapt them to different Python versions as needed.

Python List Index

To Learn about Lists – Read Python List

List Index Method

The Index function is a built-in list method that allows you to find out the index or position of an element in a sequence. In other words, this method searches for an element in the list and returns its index.

The list index() method takes three arguments: the element you want to find, and the optional (start, end) index. Its syntax is as follows:

located_at = List_name.index(element, start_pos, end_pos)

The start index is optional and defaults to 0. If the element is found, the method returns its index. If the element is not found, the method raises a ValueError exception.

ItemDescription
Parameters
element

The list element we want to find.
start_posIt is optional and refers to the position where the search begins.
end_posIt is also optional and specifies the position where the search has to end.
Return value
located_at

An integer value refers to the position of the element found in the list.
Error
ValueError

When the list index method fails to find the element, it throws the ValueError.

Also read: How to extend a list in Python

Please note that you can provide any input such as a list, a tuple, or a substring. See the below example.

>>> myList = ['1', '11', 1, 'a', 'x', 1.1]
>>> myList.index(1)
2
>>> myList.index('x')
4

How does the Python list Index() function work?

It takes one input which is the element for which you want the index or position as the output.

This method searches for the element in the list and returns the index that matches its value else raises the ValueError error.

While searching for substrings, it raises the following error.

"Substring not found"
>>> first = 'Python is the language of the future.'
>>> print(first.index('lang', 10))
14
>>> print(first.index('invalid', 10))
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
print(first.index('invalid', 10))
ValueError: substring not found
>>>

The flowcharts below attempt to explain the flow of the list index in Python:

For elements in the list:

Python List Index Method Flowchart for List element

For characters in the string:

Python List Index Method Flowchart for Substring

Program Examples

Here are some examples of code calling the Python list index method. Practice with these as much as you can to excel in Python programming skills. In case, you feel to train more, try our 40 Python exercises.

Using the wrong element

myList = [2,3,4,5,6]

myList.index(1)

The output is:

Traceback (most recent call last):
File "C:\Python\Python35\test.py", line 3, in <module>
myList.index(1)
ValueError: 1 is not in list

Find the element index in a tuple

myList = [2,3,(3,4),5]

print(myList.index((3,4)))

The result is:

2

Key Facts

Here are important facts about the Python list index() method presented in the table below:

AspectDescription
Nameindex() method
PurposeTo find the index (position) of the first occurrence of a specified element in a list.
InputAccepts a single argument, the element to search for in the list.
OutputReturns the index (position) of the first occurrence of the element.
Search BehaviorSearches the list from the beginning to find the first match. If not found, raises a ValueError.
Optional ParametersCan take optional parameters for specifying a starting and ending index for the search.
Indexing Starts at 0The first element in the list has an index of 0, the second has an index of 1, and so on.
Error HandlingRaises a ValueError if the specified element is not found in the list.
Common Use CasesUsed to locate the position of a specific element in a list, often for subsequent operations.
Case SensitivityMatches elements based on their exact value, including case sensitivity (e.g., ‘A’ ≠ ‘a’).
Multiple OccurrencesReturns the index of the first occurrence only. To find all occurrences, use a loop.

The index() method is a straightforward way to find the position of an element within a Python list, aiding in various list-based operations.

Also Read: How to use list insert in Python

Use cases for Python list index method

Here are some use cases where the Python list index can be useful:

  • Finding the position of an element in a list: This is the most common use case for the list.index() method. For example, you could use it to find the position of a student’s name in a list of students or to find the position of a date in a list of birthdays.
  • Removing an element from a list by its index: You can use the list.index() method to find the index of an element in a list, and then use the list.remove() method to remove the element at that index. For example, you could use this to remove a student from a list of students or to remove a date from a list of birthdays.
  • Slicing a list by its index: You can use the list.index() method to find the index of the start of a slice, and then use the list[start: end] notation to slice the list. For example, you could use this to slice a list of students to get a list of students from a particular class or to slice a list of birthdays to get a list of birthdays from a particular month.
  • Sorting a list by its index: You can use the list.sort() method to sort a list, and pass the list.index() method as a key function. This will sort the list based on the index of the elements. For example, you could use this to sort a list of students by their last name or to sort a list of birthdays by their date.

We hope this helps! Let us know if you have any other questions.

Best,

TechBeamers

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python Iterator Tutorial for Beginners Iterators in Python
Next Article Python List Count Method Explained with Examples List Count Method in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x