Python, First list index - previous list index then print

Viewed 60

First of all I'm not good at English please be kind to me. I've a trouble about my code. I need to substract previous list index from current list index.

Let me show you an example with my code;

xvalues = [1,1,2,3,3,3,4,1,1,1,2,3,4,5,6,6,-1,-23,-44,-512,1,2,3,4,4,4,4,4,4]

for i in xvalues:
    print([i])

I need to substract previous value from current value while in for loop. I've tried

for i in xvalues:
    print([i-1])

this but it is substract "-1" from every value in my list. I need to add this in a for loop simply;

[1]-[0] after this, do this ,[2]-[1] after ,do this [3]-[2]... 

I'm looking for someone to help me and I hope this topic save someone :)

4 Answers

In the below code, the subsequent subtractions are done by the new values. For example, the first three values of the output are, [1,0,2,...]. Notice in the 3rd place, we get the result as 2 because of 2-0, as 0 is the new value in the 2nd place.

xvalues = [1,1,2,3,3,3,4,1,1,1,2,3,4,5,6,6,-1,-23,-44,-512,1,2,3,4,4,4,4,4,4]

for i in range(1, len(xvalues)):
  xvalues[i] = xvalues[i] - xvalues[i-1]

"I need to substract previous list index from current list index."

Important Note:

[1]-[0] after this, do this ,[2]-[1] after ,do this [3]-[2]... 

You can try this.

xvalues = [1,1,2,3,3,3,4,1,1,1,2,3,4,5,6,6,-1,-23,-44,-512,1,2,3,4,4,4,4,4,4]

for i,item in enumerate(xvalues):
    if i > 0:
        previous = xvalues[i-1]#previous = item
        print(f"{item}-({previous})")
        sub = item - previous
        print("Answer: ",sub,"\n")

OUTPUT:

1-(1)
Answer:  0 

2-(1)
Answer:  1 

3-(2)
Answer:  1 

3-(3)
Answer:  0 

3-(3)
Answer:  0 

4-(3)
Answer:  1 

1-(4)
Answer:  -3 

1-(1)
Answer:  0 

1-(1)
Answer:  0 

2-(1)
Answer:  1 

3-(2)
Answer:  1 

4-(3)
Answer:  1 

5-(4)
Answer:  1 

6-(5)
Answer:  1 

6-(6)
Answer:  0 

-1-(6)
Answer:  -7 

-23-(-1)
Answer:  -22 

-44-(-23)
Answer:  -21 

-512-(-44)
Answer:  -468 

1-(-512)
Answer:  513 

2-(1)
Answer:  1 

3-(2)
Answer:  1 

4-(3)
Answer:  1 

4-(4)
Answer:  0 

4-(4)
Answer:  0 

4-(4)
Answer:  0 

4-(4)
Answer:  0 

4-(4)
Answer:  0 

You could use zip:

xvalues = [1,1,2,3,3,3,4,1,1,1,2,3,4,5,6,6,-1,-23,-44,-512,1,2,3,4,4,4,4,4,4]

for x1, x2 in zip(xvalues, xvalues[1:]):
    print(x2-x1)

To clarify the syntax:

[1] creates a new list containing 1, which is not what you want.

Let's have x = [10, 20, 30], list named x containing 10, 20, 30. Then to access its values, we use x[pos]. Get whatever value is in list x at position pos. The position is usually called index.

x[0]  # returns 10
x[1]  # returns 20
x[2]  # returns 30

Every other positive index throws error IndexError: list index out of range.

We can also access the index by variable

i = 2
x[i]  # returns 30

As an answer, I recommend using zip suggested by Myccha ;).

Related