Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: converting list of lists to tuples of tuples

Tags:

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([])   
like image 833
pythonnnoob Avatar asked Mar 31 '11 21:03

pythonnnoob


People also ask

How do I turn a list of lists into tuples?

To convert a list of lists to a list of tuples: Pass the tuple() class and the list of lists to the map() function. The map() function will pass each nested list to the tuple() class. The new list will only contain tuple objects.

How do you convert a list to a tuple of tuples?

A simple way to convert a list of lists to a list of tuples is to start with an empty list. Then iterate over each list in the nested list in a simple for loop, convert it to a tuple using the tuple() function, and append it to the list of tuples.

Can we convert list to tuple in Python?

Using the tuple() built-in function An iterable can be passed as an input to the tuple () function, which will convert it to a tuple object. If you want to convert a Python list to a tuple, you can use the tuple() function to pass the full list as an argument, and it will return the tuple data type as an output.

How do you convert a tuple to a list of tuples in Python?

To convert a tuple to list in Python, use the list() method. The list() is a built-in Python method that takes a tuple as an argument and returns the list. The list() takes sequence types and converts them to lists.


1 Answers

To convert list_of_lists to a tuple of tuples, use

tuple_of_tuples = tuple(tuple(x) for x in list_of_lists) 
like image 168
Sven Marnach Avatar answered Oct 15 '22 15:10

Sven Marnach