0

I am very simply trying to refer to the value of the previous item when using the enumerate function in Python. I don't know the syntax and cannot find it online. Help much appreciated. Thanks.

#if the close price is > line_price, and the previous is < line_price, then increment broken_line_count

mylist = [6000,6000,6000,6200,6200]

line_price = 6100
broken_line_count = 0

for i, x in enumerate(mylist):

    if x>line_price and [i-1](x)<line_price:
        broken_line_count +=1

print(broken_line_count)

Obviously [i-1](x) is incorrect, this is just illustrative of what i'm trying to achieve.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Blake
  • 41
  • 4
  • You're need `mylist[i-1]`. But a more optimized approach is to use a `zip` function for loop over the pairs so that you can have access to the both items at the same time. In this case you'll refuse of an indexing each time. – Mazdak Jan 13 '18 at 10:37
  • Also: https://stackoverflow.com/questions/5764782/iterate-through-pairs-of-items-in-a-python-list/5764807 – mkrieger1 Jan 13 '18 at 10:38
  • Thanks, that's worked great.Sorry if this is a duplicate, I looked at the link and it doesn't refer to the enumerate function which is what I thought I was struggling with. – Blake Jan 13 '18 at 10:48

0 Answers0