1

I have this question about loops. Imagine You have this data array:

list = [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1]

How would You write a loop which checks if the previous number is lower, and the next after the checked one (Condition looks like this [5,6,5]). So the loop will get to number 9 and print it or save it, whatever.

2 Answers 2

5

Using next with a generator expression:

lst = [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1]

res = next(j for i, j, k in zip(lst, lst[1:], lst[2:]) if i < j and i == k)

If you need all such numbers, use a list comprehension instead:

res = [j for i, j, k in zip(lst, lst[1:], lst[2:]) if i < j and i == k]

If you need a condition that will show all numbers that are higher than their previous and next ones:

lst = [1,2,3,4,3,2,3,1,2,1,2,3,4,5,6,7,8,6]

res = [j for i, j, k in zip(lst, lst[1:], lst[2:]) if i < j > k]

[4, 3, 2, 8] is printed.

Explanation

  • You can iterate the list with shifted versions of itself via zip.
  • For each triplet, test your two conditions.
  • Use next to extract such triplets; if no such triplet exists, you will meet StopIteration error.
  • Never name a variable after a built-in, e.g. use lst instead of list.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You so much for that explanation. Well, my problem is much more complex. Can I ask You to check my other thread? Maybe You'll have some ideas for that problem. stackoverflow.com/questions/50647094/…
1

You could just write a simple loop that checks the previous number is less than the current number, and the next number is equal to the previous number:

lst = [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1]

for i in range(len(lst)):
    if lst[i-1] < lst[i] and lst[i-1] == lst[i+1]:
        print(lst[i])

# 9

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.