How to Find the Index of an Item in Python Lists

[ad_1]

In this information, you’ll find out how to to find the index of an component in a Python record, each the usage of easy iterations and a built-in record manner index().

When operating with Python lists, it’s possible you’ll want to to find out the index at which a selected merchandise happens. You can do that by way of:

  • Looping thru the record and checking if the merchandise at the present index is equivalent to the specific price
  • Using the built-in record manner index()

You’ll be informed each of the above in this instructional. Let’s get began.👩🏽‍💻

Python Lists, Revisited

In Python, an inventory is a suite of pieces—of the similar or other knowledge sorts. They are mutable; you’ll adjust them in position with no need to create a brand new record.

Consider this case culmination: an inventory of 5 other culmination.

culmination = ["apple","mango","strawberry","pomegranate","melon"]

You can get the period of any Python object by way of the usage of the built-in len() serve as. So you’ll name the len() serve as with the record object (culmination) as the argument to get its period, as proven underneath.

len(culmination)
# Output: 5

 We’ll use the culmination record as a operating instance in this instructional.

Indexing in Python Lists

Python follows 0 indexing. So in any Python iterable, the first merchandise is at index 0, the 2d merchandise is at index 1, and so forth. If the period of the iterable is okay, then the final thing is at the index okay - 1.

In Python, you’ll use the vary() serve as to get indices as you loop thru iterables.

Note: When you loop thru vary(okay), you get the indices 0,1,2,…,(k-1). So by way of environment okay = len(record), you’ll get the record of all legitimate indices.

The following code cellular explains this.

for i in vary(len(culmination)):
  print(f"i:i, fruit[i] is culmination[i]")

# Output
i:0, fruit[0] is apple
i:1, fruit[1] is mango
i:2, fruit[2] is strawberry
i:3, fruit[3] is pomegranate
i:4, fruit[4] is melon

Now that we have got lined the fundamentals of Python lists let’s find out how to to find the index of an merchandise in an inventory.

python-find-in-list

Find Index of a List Item by way of Iteration Using for Loops

Let’s imagine the record culmination from the earlier phase. We’ll find out how to to find the index of a particular merchandise in this record by way of iteration the usage of for loop.

Using for Loop and vary() Function

Let’s repair goal: the price we’re on the lookout for in the record.

You can use for loop and vary() serve as to get the record of indices from 0 to len(culmination) - 1.

  • Loop thru the record of culmination having access to each and every index.
  • Check if the merchandise at the present index i is equivalent to the goal.
  • If True, print out that the goal has been discovered at the index i.
culmination = ["apple","mango","strawberry","pomegranate","melon"]

goal = "mango"

for i in vary(len(culmination)):
  if culmination[i] == goal:
   print(f"goal discovered at index i")

# Output
mango discovered at index 1

In this case, the goal string 'mango' seems precisely as soon as (at index 1) in the record culmination.

However, on occasion the goal price seems greater than as soon as or does now not seem in any respect. To care for those circumstances, let’s adjust the above looping and wrap the contents inside of a serve as known as find_in_list.

Understanding the Function Definition

The serve as find_in_list has two parameters:

  • goal: the price you might be on the lookout for, and
  • py_list: the Python record that you’re looking out thru.
def find_in_list(goal,py_list):
  target_indices = []
  for i in vary(len(culmination)):
    if culmination[i] == goal:
      target_indices.append(i)  
  if target_indices == []:
    print("Sorry, goal now not discovered!")
  else:
    print(f"goal is located at indices target_indices")

In the serve as frame, we initialize an empty record target_indices. We loop thru the record and get right of entry to the record pieces. If the goal has been discovered at a selected index, we upload that index to the target_indices record the usage of the append() manner.

Note: In Python, record.append(merchandise) provides merchandise to the finish of record.

  • If the goal isn’t discovered, then target_indices is an empty record; the consumer is notified that the goal isn’t provide in the record.
  • If the goal is located at a couple of index, then target_indices comprises all the ones indices.

Next, let’s redefine the culmination record as proven.

This time we’re on the lookout for the goal string 'mango', which happens two times—at indices 1 and four.

culmination = ["apple","mango","strawberry","pomegranate","mango","melon"]
goal = "mango"
find_in_list(goal,culmination)

# Output
mango is located at indices [1, 4]

On calling the serve as find_in_list with goal and culmination as the arguments, we see that each the indices are returned.

goal = "turnip"
find_in_list(goal,culmination)

# Output
Sorry, goal now not discovered!

If you attempt on the lookout for 'turnip' which isn’t provide in the culmination record, you get a message that the goal has now not been discovered.

Using for Loop and enumerate() Function

In Python, you’ll use the enumerate() serve as to get right of entry to each the index and the pieces concurrently—with no need to use the vary() serve as.

The following code cellular presentations how you’ll use the enumerate() serve as to get each the indices and the pieces.

culmination = ["apple","mango","strawberry","pomegranate","mango","melon"]
for index,fruit in enumerate(culmination):
  print(f"Index index: fruit")

# Output
Index 0: apple
Index 1: mango
Index 2: strawberry
Index 3: pomegranate
Index 4: mango
Index 5: melon

Now, let’s rewrite the Python serve as to to find the index of pieces in the record the usage of enumerate() serve as.

def find_in_list(goal,py_list):
  target_indices = []
  for index, fruit in enumerate(culmination):
   if fruit == goal:
    target_indices.append(index) 
  if target_indices == []:
    print("Sorry, goal now not discovered!")
  else:
    print(f"goal is located at indices target_indices")

As with the earlier phase, you’ll now name the find_in_list serve as with legitimate arguments.

You can translate the above serve as definition into an an identical record comprehension and we’ll do this in the subsequent phase.

Find Index of a List Item by way of Iteration Using List Comprehension

List comprehensions in Python permit you to create lists from current lists in keeping with some situation. Here’s the normal assemble:

new_list = [<output> for <items in existing iterables> if <condition is true>] 

The determine underneath describes how to determine the components of record comprehension; the usage of this, you’ll convert the serve as find_in_list to an inventory comprehension.

python-find-in-list

Using the above, the expression for record comprehension to create goal indices is as follows.

target_indices = [index for index,fruit in enumerate(fruits) if fruit==target]

As an workout, you’ll attempt operating the above code snippet for a couple of different examples.

Find Index of a List Item Using the index() Method

To to find the index of an merchandise in a Python record, you’ll additionally use the built-in .index() manner. Here is the normal syntax:

record.index(price,get started,finish)

Parsing the above manner:

  • price is the goal price that you’re on the lookout for.
  • get started and finish are not obligatory positional arguments; you’ll use them to seek to find the index of an merchandise in the record slice beginning at get started and lengthening up to finish - 1.

Note: The .index() manner returns handiest the index of the first prevalence of price in record. Even while you to find index of an merchandise in an inventory slice [start: end-1], this technique returns handiest the index corresponding to the first prevalence of the merchandise.

Let’s revisit our instance to know the way the .index() manner works.

culmination = ["apple","mango","strawberry","pomegranate","mango","melon"]
goal = "mango"

culmination.index(goal)
1

Even although there are two occurrences of 'mango' in the culmination record, you’ll see that handiest the index of the first prevalence has been returned.

To get the index of the 2d prevalence of mango, we will be able to seek thru the record slice beginning at index 2 and lengthening up to index 5, as proven underneath.

culmination.index(goal,2,5)
4

How to Handle ValueErrors in Python

Now let’s see what occurs should you attempt to to find the index of an merchandise that’s not provide in the record, say, 'carrot'.

goal = "carrot"

culmination.index(goal)

# Output
---------------------------------------------------------------------------
ValueError                                Traceback (most up-to-date name ultimate)
<ipython-input-17-81bd454e44f7> in <module>()
      1 goal = "carrot"
      2 
----> 3 culmination.index(goal)

ValueError: 'carrot' isn't in record

As noticed in the code cellular above, this throws a ValueError. In Python, you’ll care for this as an exception the usage of the attempt and besides blocks.

The normal syntax to use try-except is as follows.

attempt:
  # to do that
besides <ErrorType>:
  # do that to care for <ErrorType> as exception

Using the above try-except blocks, we will be able to care for ValueError as an exception.

goal = "carrot"
attempt:
  culmination.index(goal)
besides ValueError:
  print(f"Sorry, may just now not to find goal in record")

# Output
Sorry, may just now not to find carrot in record

The above code does the following:

  • If the goal is provide in the record, it returns the index of the goal.
  • If the goal isn’t provide, it handles ValueError as an exception and prints out the error message.

Summing Up

Here’s a abstract of the other strategies you’ve discovered to to find the index of an merchandise in a Python record.

  • You can use Python’s for loop and vary() serve as to get the pieces and their respective indices. Check if the pieces at the indices fit the goal.
  • You too can use the enumerate() serve as to concurrently get right of entry to the merchandise and the index. 
  • You might use each the above strategies inside of of an inventory comprehension expression.
  • To to find an merchandise’s index in an inventory, you’ll additionally use the built-in .index() manner.
  • record.index(price) returns the index of the first prevalence of price in record. If the price isn’t provide, it raises a ValueError.
  • You can seek thru a definite slice of the record the usage of record.index(price, get started, finish) to seek for the prevalence of a worth in the record slice [start:end-1]. 

Next, be informed to type a Python dictionary by way of key or by way of price. Happy Python programming!

[ad_2]

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button