-2

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.

Harry Smith
  • 125
  • 7
  • Why do you need sets for a vector subtraction? – Moses Koledoye Jul 15 '16 at 14:52
  • Why were you expecting set subtraction to translate to numeric subtraction? The [documentation for sets](https://docs.python.org/2/library/stdtypes.html#set.difference) shows clearly that `-` is used for *set difference*. Any element in `set(a) - set(b)` produces a *new* set with all elements in `set(a)` that are *not* present in `set(b)`. Since `set(a)` only contains `1`, and `1` is in `set(b)` too, you get an empty set. – Martijn Pieters Jul 15 '16 at 14:53
  • vectors are not sets, and sets are the *wrong tool* for vector operations. – Martijn Pieters Jul 15 '16 at 14:54
  • *Python tries to simplify the set by removing repeated values from the list*. No, sets are unordered collections of unique values. There is no 'try' here. – Martijn Pieters Jul 15 '16 at 14:56

1 Answers1

0

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]
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119