0

Is there a way to write the following code in a more concise (or more Pythonish) way?

[ counters[i]-counters[i-1] for i in range(1, len(counters)) ]

1 Answers1

1

You can do that using zip:

[b-a for a,b in zip(counters,counters[1:])]

Example

counters = [1,6,3,8,4,6]

print [b-a for a,b in zip(counters,counters[1:])]

[OUTPUT]
[5, -3, 5, -4, 2]
sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • 1
    If I had to guess, I'd say it is because your answer is already given in the duplicate question, betters answers are given, and your answer does not add anything that was not already there. (plus, it creates 3 extra copies of the list.) – njzk2 May 27 '14 at 14:54