2

I have a list such as this:

lst = [1, 13, 5, 23, 22, 1, 2]

And I would like to find the difference between every two adjacent elements using a lambda expression to get this:

differences = [12, -8, 18, -1, -21, 1]

How would I do this? Thank you.

Arjun Vasudevan
  • 139
  • 1
  • 8
  • 2
    Does it have to be lambda expressions? May I ask why? – Denziloe Mar 18 '17 at 00:03
  • Possible duplicate of [Iterate a list as pair (current, next) in Python](http://stackoverflow.com/questions/5434891/iterate-a-list-as-pair-current-next-in-python) – pvg Mar 18 '17 at 00:07

3 Answers3

2

Use an inline for loop with your lambda. The loop will loop over the indexes then use the indexes to access the numbers from the array provided, adding adjacent indexes.

magicSubtract = lambda lst: [(lst[i] - lst[i+1]) for i in range(0,len(lst)-1)]
print(magicSubtract([1, 13, 5, 23, 22, 1, 2]))
Neil
  • 14,063
  • 3
  • 30
  • 51
1

Or you can use map:

map(lambda pair: pair[1] - pair[0], zip(lst[:-1], lst[1:]))

apply list to the result if you want a list:

list(_)
# [12, -8, 18, -1, -21, 1]
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
0

Why lambda expression? For an in line solution you can use list comprehension:

[lst[i+1]-lst[i] for i in range(len(lst)-1)]
Mikedev
  • 316
  • 1
  • 8