You will have to first flatten the irregularly nested list. Below are 2 solutions that will handle any depth, irregularly nested lists.
Using collections
Try collections for flattening the irregular deep nested list
-
import collections
def flatten(x):
if isinstance(x, collections.Iterable):
return [a for i in x for a in flatten(i)]
else:
return [x]
a = [1, 2, 3, [1, [2, 4]]] #Irregular deep nested list
out = set(flatten(a))
out
{1, 2, 3, 4}
More details here.
Using recursion
For lists that are nested deeper, you can use recursion
-
def flatten(S):
if S == []:
return S
if isinstance(S[0], list):
return flatten(S[0]) + flatten(S[1:])
return S[:1] + flatten(S[1:])
a = [1, 2, 3, [1, [2, 4]]] #Irregular deep nested list
out = set(flatten(a))
out
{1, 2, 3, 4}
More details here.
One-liner with recursion
If like me, you prefer using one-liners, try this lambda function with recursion -
f = lambda *n: (e for a in n for e in (f(*a) if isinstance(a, (tuple, list)) else (a,)))
out = set(f(a))
out
{1, 2, 3, 4}
More details here.