1

pretty simple question I guess, sorry I'm pretty new to Python. So I have a given list and want to iterate through it. I want to compare every item in the list to the upcoming one. Unfortunately it does not work for me.

values = [45, 24, 35, 31, 40, 38, 11]
for i in values:
if values(i+1) > values(i):
    print(str(i+1) + " > " + str(i))
else:
    print(str(i+1) + " < " + str(i))

(As an example, for the first step I would want to have 45 compared to 24)

1337_N00B
  • 47
  • 8
  • First of all list indexing is using `[i]` notation, secondly `for i in thing` will loop through the *elements* not the *indices*. For the latter you want `for i in range(len(values)-1)` the `-1` is so you don't go out of bounds for your last iteration – Cory Kramer May 16 '18 at 19:17
  • You have some basic Python syntax flaws in your code. Try another go at reading a Python tutorial such as [the official one](https://docs.python.org/3/tutorial/index.html) and come back to your question then. – Ziyad Edher May 16 '18 at 19:19

3 Answers3

0
for idx in range(len(values) - 1):
    current_value = values[idx]
    next_value = values[idx+1]


    print("Current value: ", current_value)
    print("Next value: ", next_value)
Lev
  • 1,698
  • 3
  • 18
  • 26
0

I assume 1) you want to compare consecutive elements by the code segment given. 2) You want to print the actual value rather than the index.

for i in range(len(values)-1):
    if values[i+1] > values[i]:
        print(str(values[i+1]) + " > " + str(values[i]))
    else:
        print(str(values[i+1]) + " < " + str(values[i]))

You need to add range(len(values)-1) so that you i would be the index rather than the value at the position.

Sach
  • 845
  • 3
  • 9
  • 22
0

A quick rewrite:

values = [45, 24, 35, 31, 40, 38, 11]


for i in range (len(values)-1):
    if values[i] < values[i+1 ]:
        print(str(values [i+1]) + " > " + str(values[i]))
    else:
        print(str(values[i+1]) + " < " + str(values[i]))
Watty62
  • 602
  • 1
  • 5
  • 21