Billy Grande
Billy Grande

Reputation: 587

convert lists to tuples converting also the lists inside the list

A simple way to convert a list to a tuple in Python is this:

tuple1=tuple(list1)

But if the list1 contains one or more lists, they remain the same. Is there a way that we can convert them as well? E.g.

list1=[1,3,'abc',[3,4,5]]

goes to:

tuple1=(1,3,'abc',(3,4,5))

Upvotes: 1

Views: 666

Answers (2)

Eric
Eric

Reputation: 97601

Recursion is all you need here:

def convert(l):
    return tuple(convert(x) for x in l) if type(l) is list else l
>>> convert([1,3,'abc',[3,4,5]])
(1, 3, 'abc', (3, 4, 5))
>>> convert([[[[[[]]]]]])
((((((),),),),),)
>>> convert(42)
42

Upvotes: 8

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251001

use isinstance() to see if an element is a list or not:

In [64]: lis=[1,3,'abc',[3,4,5]]

In [66]: tuple(tuple(x) if isinstance(x,list) else x for x in lis)
Out[66]: (1, 3, 'abc', (3, 4, 5))

Upvotes: 1

Related Questions