I am trying to convert a nested list of lists into a list of tuples in Python 3.3. However, it seems that I don't have the logic to do that.
The input looks as below:
>>> nested_lst = [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]
And the desired ouptput should look as exactly as follows:
nested_lst_of_tuples = [('tom', 'cat'), ('jerry', 'mouse'), ('spark', 'dog')]
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.
Use the map() Function to Convert a Tuple to a List in Python. The map() function can apply a function to each item in an iterable. We can use it with the list() function to convert tuple containing tuples to a nested list.
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.
tuple1 = ("Ram", "Arun", "Kiran") tuple2 = (16, 78, 32, 67) tuple3 = ("apple", "mango", 16, "cherry", 3.4) Lists can contain multiple items of different types of data. We can also combine lists data into a tuple and store tuples into a list.
Convert a list into a tuple in Python. 1 With tuple. This is a straight way of applying the tuple function directly on the list. The list elements get converted to a tuple. 2 Example. 3 Output. 4 With *. 5 Example. More items
The task is to convert a nested list into a single list in python i.e no matter how many levels of nesting is there in python list, all the nested has to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brackets inside.
Because some downstream code may be expecting to handle tuple and the current list has the values for that tuple. In this article we will see various ways to do that. This is a straight way of applying the tuple function directly on the list. The list elements get converted to a tuple.
Just use a list comprehension:
nested_lst_of_tuples = [tuple(l) for l in nested_lst]
Demo:
>>> nested_lst = [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']] >>> [tuple(l) for l in nested_lst] [('tom', 'cat'), ('jerry', 'mouse'), ('spark', 'dog')]
You can use map()
:
>>> list(map(tuple, [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']])) [('tom', 'cat'), ('jerry', 'mouse'), ('spark', 'dog')]
This is equivalent to a list comprehension, except that map
returns a generator instead of a list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With