Aman Mathur
Aman Mathur

Reputation: 719

How to convert a tuple of tuple or int to set in python

I have the following kind of input

tuple_of_tuple_or_int = ((3,8),4) # it may be like (4,(3,8)) also

I want to convert it to a set like

{3,8,4} # in any order

I have tried this:

[element for tupl in tuple_of_tuple_or_int for element in tupl]

But it throws the following error:

TypeError: 'int' object is not iterable

Upvotes: 0

Views: 7077

Answers (2)

Pedro Lobito
Pedro Lobito

Reputation: 98881

It's a bit overkill for your problem but it may help future users to flat nested tuples into a single tuple or list:

def flatten(T):
    if not isinstance(T,tuple): return (T,)
    elif len(T) == 0: return ()
    else: return flatten(T[0]) + flatten(T[1:])

tuple_of_tuple_or_int = ((3,8),4)

print flatten(tuple_of_tuple_or_int) # flatten tuple
# (3, 8, 4)

print list(flatten(tuple_of_tuple_or_int)) # flatten list
# [3, 8, 4]

Upvotes: 0

Dan D.
Dan D.

Reputation: 74645

You can fix that flatten with a conditional but that conditional must result in an iterable so in this we use a 1-tuple:

[element for tupl in tuple_of_tuple_or_int 
         for element in (tupl if isinstance(tupl, tuple) else (tupl,))]

This cause the input ((3,8),4) to be processed as if it was ((3,8),(4,)).

Python 2.7.3
>>> tuple_of_tuple_or_int = ((3,8),4)
>>> [element for tupl in tuple_of_tuple_or_int 
...          for element in (tupl if isinstance(tupl, tuple) else (tupl,))]
[3, 8, 4]

This could be made more general by replacing isinstance(tupl, tuple).

Upvotes: 1

Related Questions