54

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
woollybrain
  • 843
  • 1
  • 8
  • 12

2 Answers2

80

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]]
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
25

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.

Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
  • Also in Py2 `map` w/o Lambdas are faster than list-comps. :) – Bhargav Rao Jul 07 '15 at 15:16
  • 2
    @BhargavRao Probably by a negligible amount - unless you have identified this as the performance bottleneck in your code, readability should always be the priority. – Gareth Latty Jul 07 '15 at 15:17
  • I always thought `map` was more readable than list-comp. But yes, the speed diff is quite small. – Bhargav Rao Jul 07 '15 at 15:24
  • List comprehensions read more like everyday code - readability is subjective (those used to functional languages will be used to `map()`), but I'd say the only readable case for map is the simple case where you are using an existing function or type - defining a new function (including lambdas) for a `map()` is never going to be more readable than a list comprehension. (And, as you note, less performant). – Gareth Latty Jul 07 '15 at 16:10
  • just a small comment: you could convert map to list with this piece of code `[*map(list, list_of_tuples)]` instead of `list(map(list, list_of_tuples))` as the first approach is faster (you can check it `%timeit`) – Amin Ba Apr 26 '21 at 20:26