Find first occurrence in list python

Find first occurrence in list python

Improve Article

Save Article

Like Article

Many times we require to find the first occurring non-zero number to begin the processing with. This has mostly use case in Machine Learning domain in which we require to process data excluding None or 0 values. Let’s discuss certain ways in which this can be performed. Method #1 : Using next() + enumerate() The next function can be used to iterate through the list and enumerate along with it checks for the list if the number is a non zero element and returns the number of 0s before a True value i.e a non zero value. 

test_list = [ 0, 0, 5, 6, 0]

print ("The original list is : " + str(test_list))

res = next((i for i, j in enumerate(test_list) if j), None)

print ("The values till first True value : " + str(res))

Output:The original list is : [0, 0, 5, 6, 0] The values till first True value : 2

  Method #2 : Using filter() + lambda + index() Using the combination of the above functions, one can easily perform this particular task. The filter function can be used to screen out the True value that is processed by the lambda functions and index function returns the first occurrence of this. 

test_list = [ 0, 0, 5, 6, 0]

print ("The original list is : " + str(test_list))

res = test_list.index(next(filter(lambda i: i != 0, test_list)))

print ("The values till first True value : " + str(res))

Output:The original list is : [0, 0, 5, 6, 0] The values till first True value : 2


Find first occurrence in list python

Improve Article

Save Article

Like Article

Given two lists, the task is to write a Python program to extract the first element that occurs in list 1 from list 2.

Examples:

Input : test_list1 = [1, 6, 3, 7, 8, 9, 2], test_list2 = [4, 10, 8, 2, 0, 11]

Output : 8

Explanation : 8 is first element from list 2, that occurs in list 1, in 5th index.

Input : test_list1 = [1, 6, 3, 7, 8, 9, 2], test_list2 = [4, 10, 18, 12, 0, 11]

Output : None

Explanation : No element of list 2 found in list 1.

Approach : Using set() + next()

In this, initially, the check container is converted to set, and each element is checked using next() and generator expression. The next() function returns the first element matching, else if no match element is found, None is returned.

test_list1 = [1, 6, 3, 7, 8, 9, 2]

test_list2 = [4, 10, 8, 2, 0, 11]

print("The original list 1 is : " + str(test_list1))

print("The original list 2 is : " + str(test_list2))

test_list2 = set(test_list2)

res = next((ele for ele in test_list1 if ele in test_list2), None)

print("First element in list 1 from 2 : " + str(res))

Output:

The original list 1 is : [1, 6, 3, 7, 8, 9, 2] The original list 2 is : [4, 10, 8, 2, 0, 11] First element in list 1 from 2 : 8

This tutorial will discuss the methods to find the first occurrence of a substring inside a string in Python.

Use the find() Function to Find First Occurrence in Python

We can use the find() function in Python to find the first occurrence of a substring inside a string. The find() function takes the substring as an input parameter and returns the first starting index of the substring inside the main string.

This function returns -1 if the substring isn’t present in the main string.

string = "This guy is a crazy guy." print(string.find("guy"));

Output:

5

We found the first occurrence of the string "guy" inside the "This guy is a crazy guy" string. The find() function returns 5 as the starting index in this example.

Note that this function also counts a blank space as a character.

Use the index() Function to Find First Occurrence in Python

Using the index()function is similar to the previously discussed find() function, as it takes the substring as an input parameter and returns the first occurrence of the substring inside the main string’s starting index.

string = "This guy is a crazy guy." print(string.index("guy"));

Output:

5

Like the find() function, the index() function also returns 5 as the starting index of the first occurrence of the string "guy" inside "This guy is a crazy guy" string.

Use the rfind() and rindex() Functions to Find Last Occurrence in Python

The two functions discussed previously locates the substring inside the main string from left to right. If we want to locate the substring from right to left, also called the last occurrence of the substring, we can use the rfind() and rindex() functions.

These functions are similar to their counterparts discussed in the previous examples, except they look from right to left. The following code snippets show the utilization of both functions in Python.

rfind():

string = "This guy is a crazy guy." print(string.rfind("guy"));

Output:

20

rindex():

string = "This guy is a crazy guy." print(string.rindex("guy"));

Output:

20

We found the starting index of the last occurrence of the string "guy" inside the string "This guy is a crazy guy" using the rfind() and rindex() functions in Python.

DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • What would be the most elegant and efficient way of finding/returning the first list item that matches a certain criterion?

    For example, if I have a list of objects and I would like to get the first object of those with attribute obj.val==5. I could of course use list comprehension, but that would incur O(n) and if n is large, it's wasteful. I could also use a loop with break once the criterion was met, but I thought there could be a more pythonic/elegant solution.

    In this article we will discuss different ways to get index of element in list in python. We will see how to find first index of item in list, then how to find last index of item in list, or then how to get indices of all occurrences of an item in the list. Apart from this, we will also discuss a way to find indexes of items in list that satisfy a certain condition.

    Python: Get index of item in List

    To find index of element in list in python, we are going to use a function list.index(),

    list.index()

    Python’s list data type provides this method to find the first index of a given element in list or a sub list i.e.

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

    Arguments :

    • x : Item to be searched in the list
    • start : If provided, search will start from this index. Default is 0.
    • end : If provided, search will end at this index. Default is the end of list.

    Returns: A zero based index of first occurrence of given element in the list or range. If there is no such element then it raises a ValueError.

    Important Point : list.index() returns the index in a 0 based manner i.e. first element in the list has index 0 and second element in index is 1.

    Let’s use this function to find the indexes of a given item in the list,

    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)

    Output

    First Index of element "Ok" in the list : 1

    As in the list.index() we did not provided start & end arguments, so it searched for the ‘Ok‘ in the complete list. But returned the index position as soon as it encountered the first occurrence of ‘Ok‘ in the list.

    But if searched item doesn’t exists in the list, then index() will raise ValueError. Therefore we need to be ready for this kind of scenario. For example,

    list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok'] elem = 'Why' try: index_pos = list_of_elems.index(elem) print(f'First Index of element "{elem}" in the list : ', index_pos) except ValueError as e: print(f'Element "{elem}" not found in the list: ', e)

    Output

    Element "Why" not found in the list: 'Why' is not in list

    As ‘Why‘ was not present in the list, so list.index() raised ValueError.

    Python: Find index of item in list using for loop

    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.

    list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok'] elem = 'is' pos = -1 # Iterate over list items by index pos for i in range(len(list_of_elems)): # Check if items matches the given element if list_of_elems[i] == elem: pos = i break if pos > -1: print(f'Index of element "{elem}" in the list is: ', pos) else: print(f'Element "{elem}" does not exist in the list: ', pos)

    Output:

    Index of element "is" in the list is: 2

    Python: Get last index of item in list

    To get the last index of an item in list, we can just reverse the contents of list and then use index() function, to get the index position. But that will give the index of element from last. Where we want index of last occurrence of element from start. Let’s see how to that,

    list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test'] elem = 'Ok' try: # Get last index of item in list index_pos = len(list_of_elems) - list_of_elems[::-1].index(elem) - 1 print(f'Last Index of element "{elem}" in the list : ', index_pos) except ValueError as e: print(f'Element "{elem}" not found in the list: ', e)

    Output:

    Last Index of element "Ok" in the list : 3

    It gives the index of last occurrence of string ‘Ok’ in the list.

    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,

    Find indexes of all occurrences of an item in list

    Suppose we have a list of strings i.e.

    list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok']

    Now we want to find indexes of all occurrences of ‘Ok’ in the list, like this,

    [1, 3, 9]

    They are differences ways to do that, let’s see them one by one.

    Find all indices of an item in list using list.index()

    As list.index() returns the index of first occurrence of an item in list. So, to find other occurrences of item in list, we will call list.index() repeatedly with range arguments. We have created a function that uses list.index() and returns a list of indexes of all occurrences of an item in given list i.e.

    def get_index_positions(list_of_elems, element): ''' Returns the indexes of all occurrences of give element in the list- listOfElements ''' index_pos_list = [] index_pos = 0 while True: try: # Search for item in list from indexPos to the end of list index_pos = list_of_elems.index(element, index_pos) # Add the index position in list index_pos_list.append(index_pos) index_pos += 1 except ValueError as e: break return index_pos_list

    This function calls the list.index() in a loop. Initially it looks for item from 0th index in list. But when it encounters the item, then from next iteration it looks from that location onward till the end of list is reached. It keeps the indexes of matched elements in a separate list and returns that in the end.

    Now let’s use above function to find all indexes of ‘Ok’ in the list,

    list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok'] # Get indexes of all occurrences of 'Ok' in the list index_pos_list = get_index_positions(list_of_elems, 'Ok') print('Indexes of all occurrences of "Ok" in the list are : ', index_pos_list)

    Output

    Indexes of all occurrences of "Ok" in the list are : [1, 3, 9]

    Find all indexes of an item in list directly while iterating

    Instead of using list.index() function, we can directly iterate over the list elements by indexes using range() function. Then for each element it checks, if it matches with our item or not. If yes then keep its index in list i.e.

    def get_index_positions_2(list_of_elems, element): ''' Returns the indexes of all occurrences of give element in the list- listOfElements ''' index_pos_list = [] for i in range(len(list_of_elems)): if list_of_elems[i] == element: index_pos_list.append(i) return index_pos_list list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok'] # Get indexes of all occurrences of 'Ok' in the list index_pos_list = get_index_positions_2(list_of_elems, 'Ok') print('Indexes of all occurrences of a "Ok" in the list are : ', index_pos_list)

    Output

    Indexes of all occurrences of "Ok" in the list are : [1, 3, 9]

    Simple solution. But let’s look into some single line alternatives,

    Use List Comprehension to find all indexes of an item in list

    Concept is similar but instead of using for loop for iteration we can achieve same using list comprehension i.e.

    list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok'] # Use List Comprehension Get indexes of all occurrences of 'Ok' in the list index_pos_list = [ i for i in range(len(list_of_elems)) if list_of_elems[i] == 'Ok' ] print('Indexes of all occurrences of a "Ok" in the list are : ', index_pos_list)

    Output

    Indexes of all occurrences of "Ok" in the list are : [1, 3, 9]

    Use more_itertools.locate() to find all indexes of an item in list

    more_itertools.locate(iterable, pred=bool, window_size=None)

    locate() yields the index of each item in list for which given callback returns True.

    To find all the occurrences of item ‘Ok‘ in the list we will pass a lambda function to locate(), that will check if item is ‘Ok‘ or not i.e.

    from more_itertools import locate list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok'] # Use more_itertools.locate() to find all indexes of an item 'Ok' in list index_pos_list = list(locate(list_of_elems, lambda a: a == 'Ok')) print('Indexes of all occurrences of a "Ok" in the list are : ', index_pos_list)

    Output

    Indexes of all occurrences of "Ok" in the list are : [1, 3, 9]

    locate() yields the indexes of elements in the list for which given predicate is True. So, in our case it yields the indexes of ‘Ok’ in the list. We collected those indexes in a list.

    Find indexes of items in a list that satisfy certain conditions

    Suppose we want to find indexes of items in a list that satisfy certain condition like indexes of items in a list of strings whose length is less than 3. To do that we have created a generic function i.e.

    def get_index_positions_by_condition(list_of_elems, condition): ''' Returns the indexes of items in the list that returns True when passed to condition() ''' index_pos_list = [] for i in range(len(list_of_elems)): if condition(list_of_elems[i]) == True: index_pos_list.append(i) return index_pos_list

    This function accepts a list of elements and a callback function as arguments. For each element it calls the callback function and if callback() function returns True then it keeps the index of that element in a new list. In the end it returns the indexes of items in the list for which callback() returned True.

    Let’s call this function to find indexes of items in list of strings whose length are less than 3 i.e.

    list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok'] # get index position of string elements in list whose length are greater than 3 index_pos_list = get_index_positions_by_condition(list_of_elems, lambda x : len(x) < 3) print('Index positions of the string elements in list with length less than 3 : ', index_pos_list)

    Output

    Indexes of all occurrences of "Ok" in the list are : [1, 3, 9]