I'm not looking for a solution (I have two ;) ), but on insight to compare the strengths and weaknesses of each solution considering python's internals. Thanks !
With a coworker, we wish to extract the difference between two successive list elements, for all elements. So, for list :
[1,2,4]
the expected output is :
[1,2]
(since 2-1 = 1, and 4-2 = 2).
We came with two solutions and I am not sure how they compare. The first one is very C-like, it considers the list as a table and substracts the difference between two successive list elements.
res = []
for i in range(0, len(a)-1):
res.append(a[i+1] - a[i])
The second one is (for a list "l"), I think, more pythonic :
[j - i for i,j in zip(l[:-1], l[1:])]
Though, isn't it far less efficient to build two copies of the list to then extract the differences ? How does Python handle this internally ?
Thanks for your insights !
With a generator:
def diff_elements(lst):
"""
>>> list(diff_elements([]))
[]
>>> list(diff_elements([1]))
[]
>>> list(diff_elements([1, 2, 4, 7]))
[1, 2, 3]
"""
as_iter = iter(lst)
last = next(as_iter)
for value in as_iter:
yield value - last
last = value
This has the nice properties of:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With