Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better solution to get differences between list elements [duplicate]

Tags:

python

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 !

like image 661
Jokyjo Avatar asked May 21 '26 06:05

Jokyjo


1 Answers

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:

  1. Being readable, and
  2. Working on infinitely large data sets.
like image 69
Kirk Strauser Avatar answered May 23 '26 20:05

Kirk Strauser