Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of tuples to a list of lists

Tags:

python

I've written this function to convert a list of tuples to a list of lists. Is there a more elegant / Pythonic way of doing this?

def get_list_of_lists(list_of_tuples):     list_of_lists = []                                                               for tuple in list_of_tuples:         list_of_lists.append(list(tuple))      return list_of_lists 
like image 973
woollybrain Avatar asked Feb 12 '13 11:02

woollybrain


People also ask

How do you change a list of tuples to a list?

If you're in a hurry, here's the short answer:Use the list comprehension statement [list(x) for x in tuples] to convert each tuple in tuples to a list. This also works for a list of tuples with a varying number of elements.

Can we convert list to tuple and tuple to list in Python?

tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.

How do you convert a nested tuple to a list in Python?

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


Video Answer


2 Answers

You can use list comprehension:

>>> list_of_tuples = [(1, 2), (4, 5)] >>> list_of_lists = [list(elem) for elem in list_of_tuples]  >>> list_of_lists [[1, 2], [4, 5]] 
like image 126
Rohit Jain Avatar answered Oct 07 '22 15:10

Rohit Jain


While the list comprehension is a totally valid answer, as you are just changing type, it might be worth considering the alternative, the map() built-in:

>>> list_of_tuples = [(1, 2), (4, 5)] >>> map(list, list_of_tuples) [[1, 2], [4, 5]] 

The map() built-in simply applies a callable to each element of the given iterable. This makes it good for this particular task. In general, list comprehensions are more readable and efficient (as to do anything complex with map() you need lambda), but where you want to simply change type, map() can be very clear and quick.

Note that I'm using 2.x here, so we get a list. In 3.x you will get an iterable (which is lazy), if you want a list in 3.x, simply do list(map(...)). If you are fine with an iterable for your uses, itertools.imap() provides a lazy map() in 2.x.

like image 32
Gareth Latty Avatar answered Oct 07 '22 16:10

Gareth Latty