1

This returns a type error

difference = [1, 2, 3, 4, 5]

for i in range(len(difference)-1):
    difference = difference[i+1] - difference[i]

But this works fine

difference = [difference[i+1]-difference[i] for i in range(len(difference)-1)]

What am I missing here? I thought they were the same.

  • What are you trying to do here? `difference = ...`? You're _reassigning_ `difference` entirely, when you should assign to `difference[i]`. – cs95 Apr 10 '18 at 21:39
  • We may need a canonical duplicate for these kinds of questions... I swear this gets asked about 3 times a week... – Aran-Fey Apr 10 '18 at 21:41
  • @Aran-Fey I had imagined this was going to be closed soon, hence the comment and not an answer. :p – cs95 Apr 10 '18 at 21:45

3 Answers3

5

You're reassigning the variable difference during the loop. After the first iteration, it no longer contains a list, it contains the result of difference[1] - difference[0], which is an integer.

You should create a new list for the result.

newdiff = []
for i in range(len(difference)-1):
    newdiff.append(difference[i+1] - difference[i])

The second version works because you don't reassign the variable until the list comprehension is done, not each time through the loop.

Barmar
  • 596,455
  • 48
  • 393
  • 495
1

Look at this line in the loop:

    difference = difference[i+1] - difference[i]

Here, you set the variable difference to an integer. So, on the second loop, you try to index an integer. Eg, you try to say that difference = 1[2] - 1[1], which makes no sense whatsoever. This is what the error "Integer is not subscriptable" means.

You need to make a new list, which is what the list comprehension does before changing your variable. That's why it doesn't give a type error.

I think your code should be:

for i in range(len(difference)-1):
    difference[i] = difference[i+1] - difference[i]
difference = difference[:-1] # drop last element.
AJF
  • 11,407
  • 2
  • 34
  • 59
0

Here additional way to do this with python library itertools :

from itertools import accumulate 
difference = [1, 2, 3, 4, 5]
difference = list(accumulate(difference, lambda x,y : y-x))
Take_Care_
  • 1,638
  • 19
  • 21