Home > Software engineering >  How do I return the first position of a value in a list?
How do I return the first position of a value in a list?

Time:03-11

I am trying to create a function that will return the first position of 140 or higher in a list. My code will return every instance where 140 is present.

The list looks something like this [[0.1,1.2,12.2,140.1,32],[0.2,2.2,222,11,32],[142,3.2,32.2,140.3,32],[0.4,4.2,42.2,140.4,192],[0.5,5.2,52.2,14.5,32]]

This is the function:

def val_return(prices):
    for i in range (0, len(prices)):
        for j in range (0, len(prices[i])):
            if prices[i][j] > 140:
                return (j)
            elif prices [i][j] < 139:
                pass

CodePudding user response:

It seems that your problem is with missing = when you are comparing with 140. Also, the elif part is extra:

def val_return(prices):
   result = []
   for i in range (len(prices)):
      for j in range (len(prices[i])):
         if prices[i][j] >= 140:
            result.append(j)
            pass
   return result

The output:

[3, 2, 0, 3]

This is a more Pythonic way of doing your job:

def val_return(prices):
    return [next((each_element[1] for each_element in zip(each_row, range(len(each_row))) if each_element[0] >= 140), None) for each_row in prices]
  • Related