mihasa
mihasa

Reputation: 1017

Get unique values in List of Lists

I want to create a list (or set) of all unique values appearing in a list of lists in python. I have something like this:

aList=[['a','b'], ['a', 'b','c'], ['a']]

and i would like the following:

unique_values=['a','b','c']

I know that for a list of strings you can just use set(aList), but I can't figure how to solve this in a list of lists, since set(aList) gets me the error message

unhashable type: 'list'

How can i solve it?

Upvotes: 43

Views: 62295

Answers (6)

dlask
dlask

Reputation: 8982

array = [['a','b'], ['a', 'b','c'], ['a']]
result = {x for l in array for x in l}

Upvotes: 67

Charly Empereur-mot
Charly Empereur-mot

Reputation: 661

The 2 top voted answers did not work for me, I'm not sure why (but I have integer lists). In the end I'm doing this:

unique_values = [list(x) for x in set(tuple(x) for x in aList)]

Upvotes: 3

Tanveer Alam
Tanveer Alam

Reputation: 5275

You can use itertools's chain to flatten your array and then call set on it:

from itertools import chain

array = [['a','b'], ['a', 'b','c'], ['a']]
print set(chain(*array))

If you are expecting a list object:

print list(set(chain(*array)))

Upvotes: 24

Haresh Shyara
Haresh Shyara

Reputation: 1886

Try to this.

array = [['a','b'], ['a', 'b','c'], ['a']]
res=()
for item in array:
    res = list(set(res) | set(item))
print res

Output:

['a', 'c', 'b']

Upvotes: 1

Nir Alfasi
Nir Alfasi

Reputation: 53525

You can use numpy.unique:

import numpy
import operator
print numpy.unique(reduce(operator.add, [['a','b'], ['a', 'b','c'], ['a']]))
# ['a' 'b' 'c']

Upvotes: 4

no coder
no coder

Reputation: 2290

array = [['a','b'], ['a', 'b','c'], ['a']]
unique_values = list(reduce(lambda i, j: set(i) | set(j), array))

Upvotes: 4

Related Questions