0

Possible Duplicate:
Flatten (an irregular) list of lists in Python

I have a list in python like

l=[1,2,[3,4,5],[[4,2,4],[4,7,8]]]

I want using a set to get all unique values, but this fails

set(l)

TypeError: unhashable type: 'list'

So anybody help please? Want to use set with list of list of list etc etc THX

Community
  • 1
  • 1
user1598203
  • 103
  • 1
  • 6

2 Answers2

4

You'll need to 'unwind', or flatten the nested structure before you can put this in a set. You can use a generator for that to keep this efficient for large lists:

def flatten(lst):
    for element in lst:
        if isinstance(element, list):
            for subelement in flatten(element):
                yield subelement
        else:
            yield element

then use that generator on your list l to create a set:

set(flatten(l))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

How about this approach, you flatten the list first before you apply the set operation on it.

import collections

def flat_list(tlist):
   if isinstance(tlist, collections.Iterable):
      return [j for i in tlist for j in flat_list(i)]
   else:
      return [tlist]

then:

myl=[1,2,[3,4,5],[[4,2,4],[4,7,8]]]

print set(flat_list(myl))

gives:

set([1, 2, 3, 4, 5, 7, 8])

@MartijnPieters approach with a generator will work more efficiently with very large lists than this list comprehension based approach.

Levon
  • 138,105
  • 33
  • 200
  • 191