Python: converting list of lists to tuples of tuples

26,253

Solution 1

To convert list_of_lists to a tuple of tuples, use

tuple_of_tuples = tuple(tuple(x) for x in list_of_lists)

Solution 2

there is a python built in function: list and tuple

list( the tuple)...to conver tuple to list tuple( the list )....to convert list to tuple

Share:
26,253

Related videos on Youtube

pythonnnoob
Author by

pythonnnoob

Updated on July 09, 2022

Comments

  • pythonnnoob
    pythonnnoob almost 2 years

    A Python newbie! I need help converting a list of lists tuples of tuples.

    I want to call the append_as_tuples function, but every time I return it, it says
    it can only concatenate lists (not tuples) to lists

    Here is what I have so far:

    def append_as_tuple(t, l):
        ''' Convert list l to a tuple and append it to tuple t as a single value '''
        return t[:] + (tuple(l),)  
    
    def convert_lists(lol):
        t = []
        if type(lol) == a or type(lol) == tuple:
            return [convert_lists(lol) for i in t]
        return append_as_tuples(lol,a)
    
    #- test harness#
    
    a=[range(5), range(10,20), ['hello', 'goodbye']]  
    print a  
    print convert_lists(a)  
    print convert_lists([])  
    
    • John Machin
      John Machin about 13 years
      Your if type(lol) == a is quite wrong; it appears to work only because you have a global variable named a in your "test harness" and a is not a type instance ... so that test will be False. Without the global a, it would raise an exception.
  • Leland Hepworth
    Leland Hepworth almost 4 years
    This will covert the outermost list to a tuple (or vice versa). However, the inner lists/tuples will remain as their original type.