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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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]]
Method 2
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0