How do you find the first occurrence of an element in a list in python?

By On Thursday, October 6th, 2022 Categories : Tanya Jawab

How do you find the first occurrence of an element in a list in python? – Halo ibu dan bapak semua, Selamat datang di web Trend Wisata dot com ini. Saat ini, saya di web TrendWisata dotcom mau membagikan info yang mantap yang menjelaskan tentang How do you find the first occurrence of an element in a list in python?. Ini dia Agan dan sista melihat di bawah ini:

Sometimes you’ll have a list in python and you’d like to find the first element in that list that matches some arbitrary condition. We’ll see now how to do that.

For our example the condition is very simple, the length of a string being longer than 5 characters.

Oh and if you are interested, I also wrote a solution to find the first matching element using Perl where there
is a function called first.

Find first element using a for loop

The first solution that might come to mind is using a for loop. Grammatically I find it strange, but Python has a nice programming technique. You can add an else part to a for-loop and this else part will be executed if the loop finished “normally”, without calling break.

examples/python/first_loop.py

animals = ['snake', 'camel', 'etruscan shrew', 'ant', 'hippopotamus', 'giraffe']

for animal in animals:
    if len(animal) > 5:
        first = animal
        break
else:
    first = None
print(first)   # etruscan shrew

Find first element using filter and
next

Another way that is more compact and some people might find nicer is to use the filter function of Python. Usually we use it to create a shorter list of elements meeting some condition. In this case however we don’t need to store the result of the filter call in a variable. Instead we can call the next function. This will return the next element returned by the filter object. Which, in our case, will be the first element in the list.

The only issue is
that if there were no matching values, this call would raise an exception. Adding a second parameter to the next() call, Python will return that value. None, in our case.

I’ve added a second copy to the solution in which I’ve separated the steps: First assigning the result of filter to a variable and then calling next on it. It is there only to make it easier to understand the construct.

examples/python/first_filter.py

animals = ['snake', 'camel', 'etruscan shrew', 'ant', 'hippopotamus', 'giraffe']

first = next(filter(lambda animal: len(animal) > 5, animals), None)
print(first)
print('-------')



filtered_list = filter(lambda animal: len(animal) > 5, animals)
print(filtered_list)
first = next(filtered_list, None)
print(first)

The
output will look like this:

etruscan shrew
-------
<filter object at 0x7f1519456a00>
etruscan shrew

Show the operations

In Python 2 filter would have returned a list already checking all the values of the original list. That would be a waste of time and CPU. The filter function in Python 3 returns a filter object and only executes the filtering condition when the user actually wants to find the next element in the filtered list. You believe me (and the documentation)? Do you want to see it with your own eyes? Fair enough, let’s
try it.

In this example, instead of a lambda-function I used a function defined using def and in this function I’ve added a print-statement as well so we can see when it is executed and with what values?

examples/python/first_filter_log.py

animals = ['snake', 'camel', 'etruscan shrew', 'ant', 'hippopotamus', 'giraffe']

def condition(animal):
    print(f"len(animal)")
    return len(animal) > 5

first = next(filter(condition, animals), None)
print(first)

This is the output:

len(snake)
len(camel)
len(etruscan shrew)
etruscan shrew

As you can see it stopped calling the condition function once it encountered the first matching string.

Etruscan shrew

In case you were
wondering the Etruscan shrew is the smallest mammal by mass.

There is a shorter mammal, but this looks better.

Now we want to find indexes of all occurrences of ‘Ok’ in the list, like this,,To find index of element in list in python, we are going to use a function list.index(),,Till now we have seen, how to find index of first occurrence of an item in the list. But what if there are multiple occurrences of an item in the list and we want to know their indexes ? Let’s see how to do that,,Instead of using list.index() function, we can iterate over the list elements by index
positions, to find the index of element in list i.e.

1._

list.index(x[, start[, end]])

Suppose we have a list of strings,

# List of strings
list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok']

Now let’s find the index of the first occurrence of item ‘Ok‘ in the list,

elem = 'Ok'

# Find index position of first occurrence of 'Ok' in the list
index_pos = list_of_elems.index(elem)

print(f 'First Index of element "elem" in the list : ', index_pos)

Suggestion : 2

If you are searching for the index of the last occurrence of myvalue in mylist:

len(mylist) - mylist[::-1].index(myvalue) - 1

Perhaps the two
most efficient ways to find the last index:

def rindex(lst, value):
   lst.reverse()
i = lst.index(value)
lst.reverse()
return len(lst) - i - 1
def rindex(lst, value):
    lst.reverse()
    i = lst.index(value)
    lst.reverse()
    return len(lst) - i - 1
def rindex(lst, value):
   return len(lst) - operator.indexOf(reversed(lst), value) - 1

Both take only O(1) extra space and the two in-place reversals of the first solution are much faster than creating a reverse copy. Let’s compare it with the other solutions posted previously:

def rindex(lst, value):
   return len(lst) - lst[::-1].index(value) - 1

def rindex(lst, value):
   return len(lst) - next(i
      for i, val in enumerate(reversed(lst)) if val == value) - 1

As a small helper function:

def rindex(mylist, myvalue):
   return len(mylist) - mylist[::-1].index(myvalue) - 1

Python lists have the
index() method, which you can use to find the position of the first occurrence of an item in a list. Note that list.index() raises ValueError when the item is not present in the list, so you may need to wrap it in try/except:

try:
idx = lst.index(value)
except ValueError:
   idx = None

To find the position of the last occurrence of an item in a list efficiently (i.e.
without creating a reversed intermediate list) you can use this function:

def rindex(lst, value):
   for i, v in enumerate(reversed(lst)):
   if v == value:
   return len(lst) - i - 1 #
return the index in the original list
return None

print(rindex([1, 2, 3], 3)) # 2
print(rindex([3, 2, 1, 3], 3)) # 3
print(rindex([3, 2, 1, 3], 4)) # None

Using max + enumerate to get last element occurrence

rindex = max(i
   for i, v in enumerate(your_list) if v == your_value)

This method can be more optimized than above

def rindex(iterable, value):
   try:
   return len(iterable) - next(i
      for i, val in enumerate(reversed(iterable)) if val == value) - 1
except StopIteration:
   raise ValueError

Suggestion : 3

To find index of the first occurrence of an element in a given Python List, you can use index() method of List class with the element passed as argument.,A Python List
can contain multiple occurrences of an element. In such cases, only the index of first occurrence of specified element in the list is returned.,The element 52 is present two times, but only the index of first occurrence is returned by index() method.,The index() method returns an integer that represents the index of first match of specified element in the List.

To find index of the first occurrence of an element in a given
Python List, you can use index() method of List class with the element passed as argument.

index = mylist.index(element)

Following is the syntax of index() function with start and end positions.

index = mylist.index(x, [start[, end]])

Python Program

mylist = [21, 5, 8, 52, 21, 87]
item = 8

#search
for the item
index = mylist.index(item)

print('The index of', item, 'in the list is:', index)

Suggestion : 4

Another approach is using Python3 “index( )”
function, which searches for a given element in the given List and returns the index of its first occurrence in the list. Using “index( )” function, we find the First Occurrence, and by Using “index( )” function on the reversed List, we find the Last Occurrence.,Given a sorted array with possibly duplicate elements, the task is to find indexes of first and last occurrences of an element x in the given array. ,Add all the elements of the array to ArrayList and using indexOf() and
lastIndexOf() method we will find the first position and the last position of the element in the array.,Write a function that counts the number of times a given int occurs in a Linked List

First Occurrence = 8
Last Occurrence = 9
First Occurrence = 8
Last Occurrence = 9

Suggestion : 5

The index() method returns the first occurrence of an element in the list. In the above example, it returns 1, as the first occurrence of “Bob” is at index 1.,To recap, use the index() method to find the index of an
element in Python. You can use it the same way for lists and strings. It finds the first occurrence of a specified element in the sequence.,You can use the index() method to find the index of the first element that matches with a given search object.,This method returns the index of the first element that matches with the parameter.

For example, let’s find the first string that equals “Bob” in a list of strings:

names = ["Alice", "Bob", "Charlie"]

names.index("Bob") # Returns 1

For example,
let’s find the first occurrence of the letter w in a string:

"Hello world".index("w") # returns 6

The syntax for the index() function is as follows:

How do you find the index of an element in a list Python?

Syntax of index() Method.

Syntax: list_name.index(element, start, end).

Parameters:.

Return: Returns the lowest index where the element appears..

Error: If any element which is not present is searched, it raises a ValueError..

How do you extract the first element of a list?

To extract only first element from a list, we can use sapply function and access the first element with double square brackets. For example, if we have a list called LIST that contains 5 elements each containing 20 elements then the first sub-element can be extracted by using the command sapply(LIST,”[[“,1).

How do you find the last occurrence of an element in a list Python?

Let’s see how to find the last occurrence of an element by reversing the given list..

Initialize the list..

Reverse the list using reverse method..

Find the index of the element using index method..

The actual index of the element is len(list) – index – 1..

Print the final index..

How do you find the first occurrence of an element in a list in python? | admin | 4.5
shopee flash sale gratis ongkir
x