Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a tuple of tuples to a list of lists? [duplicate]

I would like to convert the tuple of tuples into a list of lists.

I don't want to flatten it, unlike these questions, and I don't want to make it a numpy array like in this question.

My only idea so far is to iterate the tuples with for loops and copy the values, but there must be something cleaner and more pythonic.

like image 703
Pavel V. Avatar asked Jul 07 '15 09:07

Pavel V.


People also ask

How do I turn a list of tuples into a list?

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

Can list and tuple have duplicate values?

Tuples allow duplicate members and are indexed. Lists Lists hold a collection of objects that are ordered and mutable (changeable), they are indexed and allow duplicate members. Sets Sets are a collection that is unordered and unindexed. They are mutable (changeable) but do not allow duplicate values to be held.

How do you duplicate a tuple?

Method #1 : Using * operator The multiplication operator can be used to construct the duplicates of a container. This also can be extended to tuples even though tuples are immutable.

Can we convert list to tuple and tuple to list 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.


1 Answers

Is this what you want? -

In [17]: a = ((1,2,3),(4,5,6),(7,8,9))

In [18]: b = [list(x) for x in a]

In [19]: b
Out[19]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

This is called list comprehension, and when you do list(x) where x is an iterable (which also includes tuples) it converts it into a list of same elements.

like image 170
Anand S Kumar Avatar answered Oct 09 '22 14:10

Anand S Kumar