1

From this data structure: [(1,2),(1,3),(1,4),(1,5)] I am tying to get the unique values, or [1,2,3,4,5]. What's the easy solution here?

martineau
  • 119,623
  • 25
  • 170
  • 301
Wells
  • 10,415
  • 14
  • 55
  • 85

3 Answers3

5

You can use set with list comprehension:

lst = [(1,2),(1,3),(1,4),(1,5)]

set(j for i in lst for j in i)
# {1, 2, 3, 4, 5}
Psidom
  • 209,562
  • 33
  • 339
  • 356
2

Use chain.from_iterable from the itertools module. It's generally considered to be the idiomatic way to flatten a 2D iterable as opposed to a nested list comprehension. See this question.

>>> from itertools import chain
>>> set(chain.from_iterable([(1,2),(1,3),(1,4),(1,5)]))
{1, 2, 3, 4, 5}

chain.from_iterable flattens the list and set keeps only unique values.

To convert back to a list, simply pass to the list constructor.

>>>list(set(chain.from_iterable([(1,2),(1,3),(1,4),(1,5)])))
[1, 2, 3, 4, 5]
Community
  • 1
  • 1
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
0

In your expected output the order of the unique elements follows the order of appearance. One way to do it would be (using an external library but the recipes are avaiable in the itertools-recipes section):

>>> from iteration_utilities import flatten, unique_everseen

>>> x = [(1,2),(1,3),(1,4),(1,5)]

>>> list(unique_everseen(flatten(x)))
[1, 2, 3, 4, 5]
MSeifert
  • 145,886
  • 38
  • 333
  • 352