-1

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

1 Answers1

2

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]
  • 2
    It's just a style difference, but I would use `enumerate(zip(...))` rather than `zip(enumerate(...), ...)` – Barmar Feb 09 '22 at 04:09
  • 1
    The nesting `x, (p1, p2)` seems more natural. – Barmar Feb 09 '22 at 04:10
  • Actually, `i for i in range (0, len(prices) - 1) if prices [i] < prices [i+1]` works as well right? – PythonLearner Feb 09 '22 at 14:30
  • @PythonLearner indeed it does; however, using `enumerate` when getting the index is the pythonic way (since `enumerate` is precisely made for this). Please check [this answer](https://stackoverflow.com/questions/24150762/pythonic-range-vs-enumerate-in-python-for-loop) too. –  Feb 09 '22 at 15:57