-1

I have a list [a,b,c,d] and I want to produce a list that gives me the absolute value of the substractions of every two elements.

[|a-b|, |a-c|, |a-d|, |b-c|, |b-d|, |c-d|]

Is there a function or a nice pythonic 1-liner to do this?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Atirag
  • 1,660
  • 7
  • 32
  • 60
  • 3
    Do these answer your question? [getting all pairs of values from list](https://stackoverflow.com/questions/32239255/python-getting-all-pairs-of-values-from-list) and [Calculating absolute value in Python](https://stackoverflow.com/q/32540121/4518341) – wjandrea Jul 02 '21 at 03:55
  • Also, if you're not familiar with these already, [Tuple unpacking in for loops](/q/10867882/4518341) and [list comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions). – wjandrea Jul 02 '21 at 04:01
  • use `itertools.combinations` – juanpa.arrivillaga Jul 02 '21 at 04:44

1 Answers1

1

Have you tried something like this? This is a quick way to get all combinations in a list:

>>> x = [1, 4, 9, 16]
>>> [abs(x[i]-x[j]) for i in range(len(x)) for j in range(i+1, len(x))]
[3, 8, 15, 5, 12, 7]
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
wong.lok.yin
  • 849
  • 1
  • 5
  • 10
  • @juanpa.arrivillaga My answer may not be perfect, but at least my answer is one liner and need no import packages. Also, when did the OP said he wants a combination? – wong.lok.yin Jul 02 '21 at 06:16
  • Sorry, misread your answer, your answer *does* generate the combinations in a list, in which case, iterating over the ranges makes sense. My apologies again. I will say, though, importing from the standard library rather than rolling your own implementation is a desirable thing. – juanpa.arrivillaga Jul 02 '21 at 07:28