0

Is it possible to use set operation for a 2D array in python. For example,

>>> a = [['a', 's'], 
         ['a', 'b'], 
         ['a', 's']]
>>> print(set(a))
Traceback (most recent call last):                                                                                                               
File "main.py", line 5, in <module>                                                                                                            
print(set(a))                                                                                                                                
TypeError: unhashable type: 'list'

It shows this error. I need a output of {'a', 's'}, {'a', 'b'}. So is it possible to get this output in any other method.

Deepan
  • 74
  • 1
  • 11
  • If you want the unique elements, not the unique arrays, then try creating the set of *flattened* input [using itertools.chain](https://stackoverflow.com/questions/11264684/flatten-list-of-lists/11264799) –  Jun 27 '20 at 14:44
  • My input is list of lists. So I need to do set operation for that list of lists. – Deepan Jun 27 '20 at 14:48
  • But your own expected output is the set of *elements* `{'a', 's'}`, not the set of lists `{['a','s']}`. If you really want the lists, you need to convert them into something [hashable](https://stackoverflow.com/questions/14535730/what-does-hashable-mean-in-python) -- such as a tuple, `set(tuple(t) for t in a)` -- aha you have changed the question as I'm typing this! –  Jun 27 '20 at 14:52
  • I have updated my question. I think it explain it clearly now – Deepan Jun 27 '20 at 14:54
  • I'm sorry for the confusion Mr.@mrblewog – Deepan Jun 27 '20 at 14:57

2 Answers2

0

Flatten it first:

a = [['a', 's'], 
     ['a', 's'], 
     ['a', 's']]
print(set(y for x in a for y in x))  # {'a', 's'}

EDIT: From the updated question, convert it to tuple first then convert the final output to set. Note that sets are not always arranged like the original values.

a = [['a', 's'], 
    ['a', 'b'], 
    ['a', 's']]
print([set(y) for y in set(tuple(x) for x in a)])  # [{'a', 's'}, {'a', 'b'}]
Ronie Martinez
  • 1,096
  • 9
  • 12
0

You are apparently after the distinct lists, per your clarification comment.

list objects aren't hashable in Python because, essentially, they are mutable and their hash codes can be changed by changing their data. So you want/need to make a set of hashable objects.

a = [['a', 's'], 
...          ['a', 'b'], 
...          ['a', 's']]

>>> set(tuple(t) for t in a)  # << unique tuples made of arrays in 'a'
{('a', 's'), ('a', 'b')}

>>> [list(x) for x in set(tuple(t) for t in a)] # << list of lists, will be unique by set(...)
[['a', 's'], ['a', 'b']]

>>> [set(x) for x in set(tuple(t) for t in a)] # << further, unique elements of the unique lists in a
[{'s', 'a'}, {'b', 'a'}]

But you can't make a true set of lists because of the hashing problem.