I would like to ask if the below function could be reduced by using 1 expression with lambda function. I am trying to locate the indices of the price list to see if there is an increase in prices from the previous index
def increasePrice (prices):
templist = []
for x in range (0, len(prices)):
if (prices [x] < prices [x 1]):
templist.append(x)
return templist
CodePudding user response:
Note that your code is missing an indentation (after if), missing )
, and iterates over the full length of prices
, which results in IndexError, since you index prices[x 1]
which doesn't exist at the last index. If you fix those, the below list comprehension produces the same outcome.
You could use enumerate
to get the indices along with zip
to iterate over consecutive elements in a list comprehension:
templist = [x for (x, p1), p2 in zip(enumerate(prices), prices[1:]) if p1 < p2]
You can also enumerate over the zip (thanks @Barmar):
templist = [x for x, (p1, p2) in enumerate(zip(prices, prices[1:])) if p1 < p2]