2

For example I have this lists of numbers / id's:

[1001, 1002, 1002, 1003, 1004]

how do I merge or make 1002 only one? So it would like this:

[1001, 1002,1003, 1004]

I know this pretty basic and I've been looking for a solution in Google for a while and all I see are how to merge dicts, which is not what I need. I just need to merge those same values.

Kobi K
  • 7,743
  • 6
  • 42
  • 86
albert3003
  • 55
  • 3

3 Answers3

5

You can create set from list and convert it back to list:

>>> a = [1001, 1002, 1002, 1003, 1004]
>>> a = list(set(a))
>>> a
[1001, 1002, 1003, 1004]

In case the order matters and needs to be sorted (even though in this example the output looks ordered, the result is not guaranteed to be sorted when using set), use:

>>> sorted(set(a))
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
dizballanze
  • 1,267
  • 8
  • 18
  • 1
    @dizballance, my previous statement was not about the output being sorted yes or no, it was about maintaining the *same* order as the input. So for example `5 2 9 9 1` would return `5 2 9 1` and not `1 2 5 9`. – KillianDS Apr 14 '15 at 09:27
0

If the order does not matter, you can use the set built-in function like so:

l = [1002, 1001, 1002, 1003, 1004]

list(set(l))
ny6ab
  • 1
0

Sets do not have duplicate values. You can take a list of numbers, convert it to a set, and convert it back to a list:

a = [1001, 1002, 1002, 1003, 1004]
b = list(set(a))

will result in 'b' having the value

[1001, 1002, 1003, 1004]
Irving Moy
  • 331
  • 3
  • 5