Harry Smith Harry Smith - 4 months ago 9
Python Question

Preserve list values during list-to-set conversion in Python

When one converts a list to a set in Python using the

set()
function, Python tries to simplify the set by removing repeated values from the list, as in the following example.

In [1]: list = [1,4,1]

In [2]: list
Out[2]: [1, 4, 1]

In [3]: set = set(list)

In [4]: set
Out[4]: {1, 4}


This is inconvenient when using sets to calculate properties of the list and converting back, as in the following vector subtraction example.

In [1]: a = [1,1,1]

In [2]: a
Out[2]: [1, 1, 1]

In [3]: b = [1,2,3]

In [4]: b
Out[4]: [1, 2, 3]

In [5]: list( set(a) - set(b) )
Out[5]: []


Clearly something went wrong: we were expecting the operation
{1-1, 1-2, 1-3} = {0, -1, -2}
. Instead, we have the following stored values.

In [6]: set(a)
Out[6]: {1}

In [7]: set(b)
Out[7]: {1, 2, 3}


This means we are calculating
{1-1, ?-2, ?-3} = ?
, which cannot be done.

Is there a way to retain the structure and values of a list when converting to a set in order to avoid this problem?

Clearly I am not talking about subtracting lists: I am talking about subtracting sets.

Answer

I don't see the need for set in this case. You can just zip the lists and do a subtraction like this

>>> a = [1,1,1]
>>> b = [1,2,3]
>>> [x-y for x,y in zip(a,b)]
[0, -1, -2]