Python – Find in list

Find in list

Asked on October 20, 2018 in Python.
Add Comment


  • 3 Answer(s)

       Finding the primary incidence
               There’s a instruction for that in itertools:

    def first_true(iterable, default=False, pred=None):
        """Returns the first true value in the iterable.
     
        If no true value is found, returns *default*
     
        If *pred* is not None, returns the first item
        for which pred(item) is true.
     
        """
        # first_true([a,b,c], x) --> a or b or c or x
        # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
        return next(filter(pred, iterable), default)
    

    For example, the following code finds the first odd number in a list:

    >>> first_true([2,3,4,5], None, lambda x: x%2==1)
    3
    
    Answered on October 20, 2018.
    Add Comment

    If you would like to seek out one part or None use default in next, it will not raise StopIteration if the item wasn’t found within the list:

    first_or_default = next((x for x in lst if ...), None)
    

     

    Answered on October 20, 2018.
    Add Comment

    While the solution  is pretty comprehensive, once we need to seek out associate degree item in an exceedingly list it’s typically helpful to urge its index:

    next((i for i, x in enumerate(lst) if [condition on x]), [default value])
    
    

     

    Answered on October 20, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.