banner



How To Find Index Of Item In List Python

Python Find in List – How to Find the Index of an Item or Element in a List

In this article you volition learn how to notice the index of an element contained in a list in the Python programming language.

There are a few ways to achieve this, and in this commodity you will learn three of the different techniques used to find the alphabetize of a listing chemical element in Python.

The three techniques used are:

  • finding the index using the alphabetize() list method,
  • using a for-loop,
  • and finally, using list comprehension and the enumerate() office.

Specifically, hither is what we will cover in depth:

  1. An overview of lists in Python
    1. How indexing works
  2. Use the index() method to find the alphabetize of an particular
    1.Use optional parameters with the index() method
  3. Go the indices of all occurrences of an item in a listing
    1. Utilise a for-loop to get indices of all occurrences of an item in a list
    2. Utilise listing comprehension and the enumerate() function to become indices of all occurrences of an item in a listing

What are Lists in Python?

Lists are a congenital-in data blazon in Python, and one of the most powerful data structures.

They act as containers and shop multiple, typically related, items under the same variable name.

Items are placed and enclosed inside square brackets, []. Each item within the square brackets is separated past a comma, ,.

                # a list chosen 'my_information' that contains strings and numbers my_information = ["John Doe", 34, "London", 1.76]                              

From the example in a higher place, you tin encounter that lists can contain items that are of whatsoever data blazon, meaning list elements tin be heterogeneous.

Dissimilar arrays that only shop items that are of the same type, lists let for more flexibility.

Lists are likewise mutable, which ways they are changeable and dynamic. List items can be updated, new items can be added to the list, and any item can exist removed at any fourth dimension throughout the life of the program.

An Overview of Indexing in Python

Every bit mentioned, lists are a drove of items. Specifically, they are an ordered collection of items and they preserve that set and defined order for the nearly function.

Each chemical element inside a list will have a unique position that identifies information technology.

That position is called the element's alphabetize.

Indices in Python, and in all programming languages, start at 0 and not 1.

Let's take a look at the list that was used in the previous department:

                my_information = ["John Doe", 34, "London", 1.76]                              

The list is zero-indexed and counting starts at 0.

The first list element, "John Doe", has an index of 0.
The second list chemical element, 34, has an index of i.
The third listing element, "London", has an index of 2.
The along list element, ane.76, has an index of 3.

Indices come in useful for accessing specific list items whose position (index) you know.

So, y'all can grab whatever list chemical element you want by using its alphabetize.

To access an item, get-go include the name of the list then in square brackets include the integer that corresponds to the alphabetize for the detail y'all want to access.

Here is how you would access each detail using its index:

                my_information = ["John Doe", 34, "London", ane.76]  print(my_information[0]) print(my_information[1]) print(my_information[2]) print(my_information[3])  #output  #John Doe #34 #London #1.76                              

Only what most finding the index of a listing particular in Python?

In the sections that follow y'all will run into some of the ways yous tin can find the index of list elements.

Find the Alphabetize of an Item using the List index() Method in Python

And then far you've seen how to access a value by referencing its alphabetize number.

What happens though when you lot don't know the index number and you're working with a large list?

You can give a value and find its alphabetize and in that way check the position it has inside the list.

For that, Python'due south built-in index() method is used as a search tool.

The syntax of the alphabetize() method looks similar this:

                my_list.index(item, get-go, end)                              

Permit's suspension it down:

  • my_list is the name of the listing you are searching through.
  • .index() is the search method which takes iii parameters. Ane parameter is required and the other two are optional.
  • item is the required parameter. It's the chemical element whose index yous are searching for.
  • start is the offset optional parameter. It's the index where y'all will commencement your search from.
  • stop the second optional parameter. It'due south the alphabetize where y'all will end your search.

Allow's see an instance using only the required parameter:

                programming_languages = ["JavaScript","Python","Java","C++"]  print(programming_languages.index("Python"))  #output #1                              

In the example in a higher place, the index() method only takes one statement which is the element whose index you are looking for.

Keep in mind that the statement you lot pass is case-sensitive. This means that if yous had passed "python", and not "Python", you would have received an error as "python" with a lowercase "p" is not part of the listing.

The return value is an integer, which is the alphabetize number of the listing particular that was passed as an statement to the method.

Let's look at another case:

                programming_languages = ["JavaScript","Python","Java","C++"]  impress(programming_languages.index("React"))  #output #line 3, in <module> #    impress(programming_languages.alphabetize("React")) #ValueError: 'React' is not in listing                              

If you lot endeavor and search for an item but in that location is no match in the listing you're searching through, Python will throw an fault as the return value - specifically it will return a ValueError.

This means that the detail you're searching for doesn't exist in the list.

A mode to prevent this from happening, is to wrap the call to the index() method in a try/except block.

If the value does not be, there will be a message to the panel saying it is not stored in the list and therefore doesn't be.

                programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]  try:     print(programming_languages.index("React")) except ValueError:     print("That item does not exist")      #output #That particular does not exist                              

Another way would be to check to come across if the item is inside the listing in the first identify, before looking for its index number. The output will be a Boolean value - information technology will be either Truthful or False.

                programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]  print("React" in programming_languages)  #output #False                              

How to Utilise the Optional Parameters with the index() Method

Let's take a look at the following example:

                programming_languages = ["JavaScript","Python","Coffee","Python","C++","Python"]  impress(programming_languages.index("Python"))  #output #one                              

In the list programming_languages there are three instances of the "Python" cord that is beingness searched.

Every bit a way to examination, you could work backwards every bit in this case the list is modest.

You could count and figure out their index numbers and and so reference them like y'all've seen in previous sections:

                programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]  print(programming_languages[1]) print(programming_languages[iii]) impress(programming_languages[5])  #output #Python #Python #Python                              

In that location is one at position 1, another i at position three and the last 1 is at position 5.

Why aren't they showing in the output when the alphabetize() method is used?

When the alphabetize() method is used, the render value is only the get-go occurence of the particular in the list. The rest of the occurrences are non returned.

The index() method returns only the alphabetize of the position where the item appears the first time.

You could try passing the optional start and end parameters to the index() method.

You already know that the kickoff occurence starts at index ane, then that could be the value of the start parameter.

For the end parameter you could first find the length of the list.

To discover the length, apply the len() function:

                print(len(programming_languages))   #output is half dozen                              

The value for stop parameter would then exist the length of the list minus 1. The index of the last item in a list is ever ane less than the length of the list.

And so, putting all that together, here is how you could try to become all iii instances of the particular:

                programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]  print(programming_languages.index("Python",i,5))  #output #1                              

The output still returns just the first instance!

Although the get-go and end parameters provide a range of positions for your search, the return value when using the index() method is still only the get-go occurence of the item in the list.

How to Get the Indices of All Occurrences of an Particular in A List

Use a for-loop to Get the Indices of All Occurrences of an Item in A List

Allow's take the same example that we've used and so far.

That list has 3 occurrences of the string "Python".

                programming_languages = ["JavaScript","Python","Coffee","Python","C++","Python"]                              

First, create a new, empty list.

This will exist the list where all indices of "Python" will be stored.

                programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]  python_indices = []                              

Next, use a for-loop. This is a style to iterate (or loop) through the list, and go each item in the original list. Specifically, nosotros loop over each item's index number.

                programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]  python_indices = []  for programming_language in range(len(programming_languages)):                              

Y'all first apply the for keyword.

Then create a variable, in this case programming_language, which volition act equally a placeholder for the position of each particular in the original listing, during the iterating process.

Next, you need to specify the set amount of iterations the for-loop should perform.

In this case, the loop will iterate through the total length of the list, from get-go to finish. The syntax range(len(programming_languages)) is a way to admission all items in the listing programming_languages.

The range() function takes a sequence of numbers that specify the number it should start counting from and the number it should cease the counting with.

The len() function calculates the length of the listing, so in this example counting would first at 0 and end at - but not include - 6, which is the end of the list.

Lastly, you lot need to set a logical condition.

Substantially, you lot want to say: "If during the iteration, the value at the given position is equal to 'Python', add that position to the new list I created before".

You use the suspend() method for calculation an element to a list.

                programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]  python_indices = []  for programming_language in range(len(programming_languages)):     if programming_languages[programming_language] == "Python":       python_indices.append(programming_language)  print(python_indices)  #output  #[i, three, 5]                              

Use List Comprehension and the enumerate() Office to Get the Indices of All Occurrences of an Item in A List

Some other way to find the indices of all the occurrences of a particular item is to use listing comprehension.

Listing comprehension is a way to create a new list based on an existing list.

Hither is how you would get all indices of each occurrence of the string "Python", using list comprehension:

                programming_languages = ["JavaScript","Python","Coffee","Python","C++","Python"]  python_indices  = [alphabetize for (alphabetize, item) in enumerate(programming_languages) if item == "Python"]  print(python_indices)  #[1, iii, 5]                              

With the enumerate() office you tin can store the indices of the items that meet the condition you set.

It first provides a pair (index, particular) for each chemical element in the list (programming_languages) that is passed as the argument to the office.

index is for the index number of the list item and item is for the list item itself.

Then, it acts as a counter which starts counting from 0 and increments each time the status you set is met, selecting and moving the indices of the items that meet your criteria.

Paired with the list comprehension, a new list is created with all indices of the cord "Python".

Conclusion

And there you have it! Y'all now know some of the ways to find the index of an detail, and ways to find the indices of multiple occurrences of an item, in a listing in Python.

I promise you lot plant this article useful.

To larn more about the Python programming linguistic communication, check out freeCodeCamp's Scientific Calculating with Python Certification.

Y'all'll beginning from the basics and learn in an interacitve and beginner-friendly style. You'll also build five projects at the end to put into practice and assistance reinforce what you've learned.

Thanks for reading and happy coding!



Larn to code for free. freeCodeCamp'south open source curriculum has helped more xl,000 people get jobs as developers. Get started

Source: https://www.freecodecamp.org/news/python-find-in-list-how-to-find-the-index-of-an-item-or-element-in-a-list/

Posted by: padillatront1952.blogspot.com

0 Response to "How To Find Index Of Item In List Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel