0
for i in list:
    j = i + 1
    print i - j

This will print out -1 times the length of list

What I wanted to do is to print the difference between value i and the next in the list.

Am I clear?

0

3 Answers 3

5
for i in list:

binds i to the elements of list, not its indexes. You might have meant

for i in xrange(len(list)):

or

for i, _ in enumerate(list):

Then get the element at index i with list[i].

(And please don't call a list list; that's the name of a Python built-in function.)

Sign up to request clarification or add additional context in comments.

Comments

4

Unlike JavaScript, iterating over a sequence in Python yields elements, not indexes.

for i, j in zip(L, L[1:]):
  print j - i

Comments

1

Try this:

lst = [1, 2, 3, 4]

for i in xrange(1, len(lst)):
    print lst[i-1] - lst[i]

Notice that in the line for i in list, i is an element of list, not an index. In the above code, i is indeed an index. Also, it's a bad idea calling a variable list (Python uses that name for something else). I renamed it to lst.

1 Comment

for i in xrange(1, len(lst)): print lst[i-1] - lst[i] That is exactly how I used larsmans answer.

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.