Python List index() with Example (2023)

A list is a container that stores items of different data types (ints, floats, Boolean, strings, etc.) in an ordered sequence. It is an important data structure that is in-built in Python. The data is written inside square brackets ([]), and the values are separated by comma(,).

The items inside the list are indexed with the first element starting at index 0. You can make changes in the created list by adding new items or by updating, deleting the existing ones. It can also have duplicate items and a nested list.

There are many methods available on a list, and of the important one is the index().

In this tutorial, you will learn:

  • Python List index()
  • Using for-loop to get the index of an element in a list
  • Using while-loop and list.index()
  • Using list comprehension to get the index of element in a list
  • Using Enumerate to get the index of an element in a list
  • Using filter to get the index of an element in a list
  • Using NumPy to get the index of an element in a list
  • Using more_itertools.locate() to get the index of an element in a list

Python List index()

The list index() method helps you to find the first lowest index of the given element. If there are duplicate elements inside the list, the first index of the element is returned. This is the easiest and straightforward way to get the index.

Besides the built-in list index() method, you can also use other ways to get the index like looping through the list, using list comprehensions, enumerate(), filter methods.

The list index() method returns the first lowest index of the given element.

Syntax

list.index(element, start, end)

Parameters

ParametersDescription
elementThe element that you want to get the index.
startThis parameter is optional. You can define the start: index to search for the element. If not given, the default value is 0.
endThis parameter is optional. You can specify the end index for the element to be searched. If not given, it is considered until the end of the list.

Return Value

The list index() method returns the index of the given element. If the element is not present in the list, the index() method will throw an error, for example, ValueError: ‘Element’ is not in the list.

Example: To find the index of the given element.

In the list my_list = [‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’] , we would like to know the index for element C and F.

(Video) How to Find the Index of a Python List Item?

The example below shows how to get the index.

my_list = ['A', 'B', 'C', 'D', 'E', 'F']print("The index of element C is ", my_list.index('C'))print("The index of element F is ", my_list.index('F'))

Output:

The index of element C is 2The index of element F is 5

Example: Using start and end in index()

In this example will try to limit searching for index in a list using start and end index.

my_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']print("The index of element C is ", my_list.index('C', 1, 5))print("The index of element F is ", my_list.index('F', 3, 7))#using just the startindexprint("The index of element D is ", my_list.index('D', 1))

Output:

The index of element C is 2The index of element F is 5The index of element D is 3

Example: To test index() method with an element that is not present.

When you try to search for index in the list for element that is not present ,you will get an error as shown below:

my_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']print("The index of element C is ", my_list.index('Z'))

Output:

Traceback (most recent call last):File "display.py", line 3, in <module>print("The index of element C is ", my_list.index('Z'))ValueError: 'Z' is not in list

Using for-loop to get the index of an element in a list

With the list.index() method, we have seen that it gives the index of the element that is passed as an argument.

Now consider the list as : my_list = [‘Guru’, ‘Siya’, ‘Tiya’, ‘Guru’, ‘Daksh’, ‘Riya’, ‘Guru’] . The name ‘Guru’ is present 3 times in the index, and I want all the indexes with the name ‘Guru’.

Using for-loop we should be able to get the multiple indexes as shown in the example below.

my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru'] all_indexes = [] for i in range(0, len(my_list)) : if my_list[i] == 'Guru' : all_indexes.append(i)print("Originallist ", my_list)print("Indexes for element Guru : ", all_indexes)

Output:

Originallist ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']Indexes for element Guru : [0, 3, 6]

Using while-loop and list.index()

Using a while-loop will loop through the list given to get all the indexes of the given element.

(Video) Python Lists: Indexing & Slicing

In the list : my_list = [‘Guru’, ‘Siya’, ‘Tiya’, ‘Guru’, ‘Daksh’, ‘Riya’, ‘Guru’], we need the all the indexes of element ‘Guru’.

Below given is an example shows how to get all the indexes using while-loop

my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru'] result = []elementindex = -1while True: try: elementindex = my_list.index('Guru', elementindex+1) result.append(elementindex) except ValueError: breakprint("OriginalList is ", my_list)print("The index for element Guru is ", result)

Output:

OriginalList is ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']The index for element Guru is [0, 3, 6]

Using list comprehension to get the index of element in a list

To get all the indexes, a fast and straightforward way is to make use of list comprehension on the list.

List comprehensions are Python functions that are used for creating new sequences (such as lists, dictionaries, etc.) i.e., using sequences that have already been created.

They help to reduce longer loops and make your code easier to read and maintain.

Following example shows how to do it:

my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru'] print("Originallist ", my_list)all_indexes = [a for a in range(len(my_list)) if my_list[a] == 'Guru']print("Indexes for element Guru : ", all_indexes)

Output:

Originallist ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']Indexes for element Guru : [0, 3, 6]

Using Enumerate to get the index of an element in a list

Enumerate() function is a built-in function available with python. You can make use of enumerate to get all the indexes of the element in a list. It takes input as an iterable object (i.e., an object that can be looped), and the output is an object with a counter to each item.

Following example shows how to make use of enumerate on a list to get the all the indexes for given element.

my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru'] print("Originallist ", my_list)print("Indexes for element Guru : ", [i for i, e in enumerate(my_list) if e == 'Guru'])

Output:

(Video) Python index() List Method - TUTORIAL

Originallist ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']Indexes for element Guru : [0, 3, 6]

Using filter to get the index of an element in a list

The filter() method filters the given list based on the function given. Each element of the list will be passed to the function, and the elements required will be filtered based on the condition given in the function.

Let us use the filter() method to get the indexes for the given element in the list.

Following example shows how to make use of filter on a list.

my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru'] print("Originallist ", my_list)all_indexes = list(filter(lambda i: my_list[i] == 'Guru', range(len(my_list)))) print("Indexes for element Guru : ", all_indexes)

Output:

Originallist ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']Indexes for element Guru : [0, 3, 6]

Using NumPy to get the index of an element in a list

NumPy library is specially used for arrays. So here will make use of NumPy to get the index of the element we need from the list given.

To make use of NumPy, we have to install it and import it.

Here are the steps for same:

Step 1) Install NumPy

pip install numpy

Step 2)Import the NumPy Module.

import numpy as np

Step 3)Make use of np.array to convert list to an array

(Video) Python 3.7: Index() List Method In Python

my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru'] np_array = np.array(my_list)

Step 4)Get the index of the element you want, usingnp.where()

item_index = np.where(np_array == 'Guru')[0]

The final working code with output is as follows:

import numpy as npmy_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru'] np_array = np.array(my_list)item_index = np.where(np_array == 'Guru')[0]print("Originallist ", my_list)print("Indexes for element Guru :", item_index)

Output:

Originallist['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']Indexes for element Guru : [0 3 6]

Using more_itertools.locate() to get the index of an element in a list

The more_itertools.locate() helps to find the indexes of the element in the list.This module will work with python version 3.5+. The package more_itertools has to be installed first to make use of it.

Following are the steps to install and make use of more_itertools

Step1)Install more_itertools using pip (python package manager). The command is

pip install more_itertools

Step 2) Once the installation is done, import the locate module as shown below

from more_itertools import locate

Now you can make use of locate module on a list as shown below in the example:

from more_itertools import locatemy_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru'] print("Originallist : ", my_list)print("Indexes for element Guru :", list(locate(my_list, lambda x: x == 'Guru')))

Output:

Originallist : ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']Indexes for element Guru : [0, 3, 6]

Summary:

  • The list index() method helps you to find the index of the given element. This is the easiest and straightforward way to get the index.
  • The list index() method returns the index of the given element.
  • If the element is not present in the list, the index() method will throw an error, for example, ValueError: ‘Element’ is not in list.
  • Besides the built-in list method, you can also make use of other ways to get the index like looping through the list, using list comprehensions, using enumerate(), using a filter, etc.
  • Using for-loop and while-loop to get the multiple indexes of a given element.
  • To get all the indexes, a fast and straightforward way is to make use of list comprehension on the list.
  • List comprehensions are Python functions that are used for creating new sequences.
  • They help to reduce longer loops and make your code easier to read and maintain.
  • You can make use of enumerate to get all the indexes of the element in a list.
  • Enumerate() function is a built-in function available with python. It takes input as an iterable object (i.e., an object that can be looped), and the output is an object with a counter to each item.
  • The filter() method filters the given list based on the function given.
  • Numpy library is specially used for arrays. You can make use of NumPy to get the index of the element given in the list.
  • The more_itertools.locate() is yet another python library that helps to find the indexes of the list given.

You Might Like:

  • Python OOPs: Class, Object, Inheritance and Constructor with Example
  • Python Tutorial PDF: Basics for Beginners (Download Notes)
  • Python vs JavaScript: Key Difference Between Them
  • Python readline() Method with Examples
  • Swap two numbers without using a third variable: C, Python Program

FAQs

What does index () do in Python? ›

The Python index() method helps you find the index position of an element or an item in a string of characters or a list of items. It spits out the lowest possible index of the specified element in the list. In case the specified item does not exist in the list, a ValueError is returned.

What is list indexing with an example? ›

“Indexing” means referring to an element of an iterable by its position within the iterable. “Slicing” means getting a subset of elements from an iterable based on their indices. By way of analogy, I was recently summoned to jury duty, and they assigned each potential juror a number.

What is the default of list index () in Python? ›

An index specifying where to start the search. Default is 0.

Why we should use index? ›

Indexes are used to quickly locate data without having to search every row in a database table every time a database table is accessed. Indexes can be created using one or more columns of a database table, providing the basis for both rapid random lookups and efficient access of ordered records.

What is the main use of index? ›

Index number helps the Government to formulate its price policies. They are also used to evaluate the purchasing power of money. Index numbers are also being used for forecasting business and economic activities, business cycles etc.

What does [:- 1 mean in Python? ›

For negative indexing, to display the 1st element to last element in steps of 1 in reverse order, we use the [::-1]. The [::-1] reverses the order. In a similar way, we can slice strings like this.

What is [- 1 in Python? ›

As an alternative, Python uses negative numbers to give easy access to the chars at the end of the string: s[-1] is the last char 'o', s[-2] is 'l' the next-to-last char, and so on. Negative index numbers count back from the end of the string: s[-1] is 'o' -- last char (1st from the end)

Is Python list index 0 or 1? ›

python lists are 0-indexed. So the first element is 0, second is 1, so on. So if the there are n elements in a list, the last element is n-1. Remember this!

What is [: 0 in Python? ›

It is a notation used in Numpy/Pandas. [ : , 0 ] means (more or less) [ first_row:last_row , column_0 ] . If you have a 2-dimensional list/matrix/array, this notation will give you all values in column 0 (from all rows).

How do you index all items in a list Python? ›

  1. Use a for-loop to get indices of all occurrences of an item in a list.
  2. Use list comprehension and the enumerate() function to get indices of all occurrences of an item in a list.
Feb 24, 2022

How do you check if a list has an index in Python? ›

if (0 <= index) and (index < len(list)): So, that condition checks if the index is within the range [0, length of list). Note: Python supports negative indexing.

How to do indexing in Python? ›

The Python index() method finds the index position of an item in an array or a character or phrase in a string. The syntax for this method is: string. index(item, start, end).

How do you assign a specific index to a list in Python? ›

You can use the insert() method to insert an item to a list at a specified index. Each item in a list has an index. The first item has an index of zero (0), the second has an index of one (1), and so on. In the example above, we created a list with three items: ['one', 'two', 'three'] .

How do you write an index in Python? ›

The data is written inside square brackets ([]), and the values are separated by comma(,). The items inside the list are indexed with the first element starting at index 0.

When should you not use an index? ›

Indexes should not be used on small tables. Indexes should not be used on columns that return a high percentage of data rows when used as a filter condition in a query's WHERE clause. For instance, you would not have an entry for the word "the" or "and" in the index of a book.

What do indexes tell us? ›

An index is a method to track the performance of a group of assets in a standardized way. Indexes typically measure the performance of a basket of securities intended to replicate a certain area of the market.

What is the most commonly used index? ›

The three most widely followed indexes in the U.S. are the S&P 500, Dow Jones Industrial Average, and Nasdaq Composite.

What is list [:] in Python? ›

The list() function creates a list object. A list object is a collection which is ordered and changeable. Read more about list in the chapter: Python Lists.

What is [:- 4 in Python? ›

What does the [-4:] means? The some_list[-n] syntax gets the nth-to-last element. So some_list[-4] gets the last four elements.

What does [:: 3 mean in Python? ›

With this knowledge, [::3] just means that you have not specified any start or end indices for your slice. Since you have specified a step, 3 , this will take every third entry of something starting at the first index. For example: >>> '123123123'[::3] '111'

What does list [- 1 do? ›

[-1] means the last element in a sequence, which in this is case is the list of tuples like (element, count) , order by count descending so the last element is the least common element in the original collection.

What is __ init __ in Python? ›

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

What is the difference between [:- 1 and 1 in Python? ›

The main difference between the 1 and 1. is in their type and type of the result of any equation that include float number in python will be float. That include addition subtraction multiplication exponents and even the integer division as if one operand is float answer will be of type float.

What does index [:- 1 do in Python? ›

However, Python has a unique feature called negative indexing. Negative indexing is basically the process of indexing a list from the outset with indexing starting at -1, i.e., -1 provides the list's last element, -2 provides the list's second last item, and so on.

Do indexes start at 0 or 1? ›

In computer science, array indices usually start at 0 in modern programming languages, so computer programmers might use zeroth in situations where others might use first, and so forth.

Why does Python indexing start at 0? ›

This means that the index is used as an offset. The first element of the array is exactly contained in the memory location that array refers (0 elements away), so it should be denoted as array[0].

Why do we use == in Python? ›

The == operator helps us compare the equality of objects. The is operator helps us check whether different variables point towards a similar object in the memory. We use the == operator in Python when the values of both the operands are very much equal. Thus, the condition would become true here.

What does array [: 0 mean? ›

It means an array with zero length.

What is tuple in Python? ›

Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is ordered and unchangeable.

How do you find the index of a value in an array in Python? ›

How to Search Through an Array in Python. You can find out an element's index number by using the index() method. You pass the value of the element being searched as the argument to the method, and the element's index number is returned.

How do you check the index of an element in a list? ›

Conclusion
  1. The index of an element in a list can be found using the list. index() method.
  2. The start and end parameters of the list. index() method are optional.
  3. If the element is not found in the list, the list. ...
  4. We can also find the index of an element in a list by iterating through the list till the element is found.
Jul 24, 2022

How do I know if I am indexed or not? ›

Checking If Your Site is Indexed by Search Engines
  1. To see if search engines like Google and Bing have indexed your site, enter "site:" followed by the URL of your domain. ...
  2. The results show all of your site's pages that have been indexed, and the current Meta Tags saved in the search engine's index.

How do I check indexes? ›

Your answer

To see indexes for all tables within a specific schema you can use the STATISTICS table from INFORMATION_SCHEMA: SELECT DISTINCT TABLE_NAME, INDEX_NAME FROM INFORMATION_SCHEMA. STATISTICS WHERE TABLE_SCHEMA = 'your_schema'; Removing the where clause will show you all indexes in all schemas.

Is index () a string method Python? ›

The python string index() method is used to return the index of the input string where the substring is found. Basically, it helps us to find out if the specified substring is present in the input string. This method takes the substring that is to be found as a mandatory parameter.

How do I run indexing? ›

Click the Start button, then click Control Panel. In the search box, type Indexing Options, and then press Enter. In the Indexing Options dialog box, click Modify. Select the drives that you want to index, and then select OK.

What are the two types of indexing in Python? ›

Basic Slicing and Advanced Indexing in NumPy Python - GeeksforGeeks.

How do you add a value to a list at a specific index? ›

Use the insert() function(inserts the provided value at the specified position) to insert the given item at the specified index into the list by passing the index value and item to be inserted as arguments to it.

How do I pick a random index from a list in Python? ›

Use the random.sample() function when you want to choose multiple random items from a list without repetition or duplicates. There is a difference between choice() and choices() . The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.

How do I print just the index of a list in Python? ›

Arrays in Python start indexing at 0 , so you have to have index(item)+1 to start printing the indexes at 1 instead of 0 (otherwise you would get 0 lol and 1 hey , etc.). The ,item concatenates the string representation of the item with what is preceding the comma, otherwise it would just print out the index.

How do you write an index function? ›

INDEX(reference, row_num, [column_num], [area_num])

The reference form of the INDEX function has the following arguments: reference Required. A reference to one or more cell ranges. If you are entering a non-adjacent range for the reference, enclose reference in parentheses.

How do you write an index example? ›

How to Write an Index
  1. Read the book. The first step may seem obvious, but it's important to do a thorough readthrough of any book before you start on the indexing process. ...
  2. Use indexing software. ...
  3. Mark up the book. ...
  4. Address formatting questions. ...
  5. Make index entries. ...
  6. Order your index entries. ...
  7. Edit your index.
Aug 9, 2021

How is an index written? ›

An index is a list of all the names, subjects and ideas in a piece of written work, designed to help readers quickly find where they are discussed in the text. Usually found at the end of the text, an index doesn't just list the content (that's what a table of contents is for), it analyses it.

What is index type in Python? ›

In DataFrame the row labels are called index. Series is a one-dimensional array that is capable of storing various data types (integer, string, float, python objects, etc.). We can easily convert the list, tuple, and dictionary into Series using the series() method. In Series, the row labels are called the index.

Is index 0 or 1 in Python? ›

Indexing in Python starts at 0, which means that the first element in a sequence has an index of 0, the second element has an index of 1, and so on.

How to create index in Python? ›

Set index using a column
  1. Create pandas DataFrame. We can create a DataFrame from a CSV file or dict .
  2. Identify the columns to set as index. We can set a specific column or multiple columns as an index in pandas DataFrame. ...
  3. Use DataFrame.set_index() function. ...
  4. Set the index in place.
Mar 9, 2021

How do you index data? ›

To index numerical data, values must be adjusted so they are equal to each other in a given starting time period. By convention, this value is usually 100. From there on, every value is normalized to the start value, maintaining the same percentage changes as in the nonindexed series.

What is [:- 1 in Python? ›

For negative indexing, to display the 1st element to last element in steps of 1 in reverse order, we use the [::-1]. The [::-1] reverses the order. In a similar way, we can slice strings like this.

What is list [- 1 in Python? ›

[-1] means the last element in a sequence, which in this is case is the list of tuples like (element, count) , order by count descending so the last element is the least common element in the original collection.

Videos

1. Python list indexing - All needed about list index
(PyNOOB)
2. How to Find Position in List (Index) | Python Tutorial | ProgrammerParker
(DevMecha)
3. Python List index() - Everything You Need to Know (and some more)
(Finxter - Create Your Six-Figure Coding Business)
4. Python Basics List Index Method
(Python Basics)
5. Python 72 List Index
(John Hammond)
6. Lists and Using List Index in Python (Python for Beginners) | Part 15
(Max Goodridge)
Top Articles
Latest Posts
Article information

Author: Wyatt Volkman LLD

Last Updated: 02/23/2023

Views: 5731

Rating: 4.6 / 5 (66 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Wyatt Volkman LLD

Birthday: 1992-02-16

Address: Suite 851 78549 Lubowitz Well, Wardside, TX 98080-8615

Phone: +67618977178100

Job: Manufacturing Director

Hobby: Running, Mountaineering, Inline skating, Writing, Baton twirling, Computer programming, Stone skipping

Introduction: My name is Wyatt Volkman LLD, I am a handsome, rich, comfortable, lively, zealous, graceful, gifted person who loves writing and wants to share my knowledge and understanding with you.