Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get unique values in List of Lists in python

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?

like image 317
mihasa Avatar asked Jun 01 '15 04:06

mihasa


People also ask

How do I get a list of unique lists?

In the first step convert the list to x=numpy. array(list) and then use numpy. unique(x) function to get the unique values from the list. numpy.

What does unique () do in Python?

unique() function. The unique() function is used to find the unique elements of an array. Returns the sorted unique elements of an array.


2 Answers

array = [['a','b'], ['a', 'b','c'], ['a']] result = {x for l in array for x in l} 
like image 74
dlask Avatar answered Oct 05 '22 16:10

dlask


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))) 
like image 23
Tanveer Alam Avatar answered Oct 05 '22 15:10

Tanveer Alam