I want to convert list into list of list. Example:
my_list = ['banana', 'mango', 'apple']
I want:
my_list = [['banana'], ['mango'], ['apple']]
I tried:
list(list(my_list))
Given a list of strings, write a Python program to convert each element of the given list into a sublist. Thus, converting the whole list into a list of lists. Use another list ‘res’ and a for a loop. Using split () method of Python we extract each element from the list in the form of the list itself and append it to ‘res’. Finally, return ‘res’.
A list can contain multiple lists of different type as well as similar type elements such as data frames, vectors, matrices etcetera but accessing those elements become a little difficult task. Therefore, it is better to convert a list that contain multiple lists into a single list and it can be done using unlist function.
This is a quite simple problem but can have a good amount of application due to certain constraints of python language. Because tuples are immutable, they are not easy to process whereas lists are always a better option while processing. Let’s discuss certain ways in which we can convert a list of tuples to list of list.
You can use a list comprehension, the itertools library, or simply loop through the list of lists adding each item to a separate list, etc. Let’s see them in action through examples followed by a runtime assessment of each. 1. Naive method – Iterate over the list of lists
Use list comprehension
[[i] for i in lst]
It iterates over each item in the list and put that item into a new list.
Example:
>>> lst = ['banana', 'mango', 'apple']
>>> [[i] for i in lst]
[['banana'], ['mango'], ['apple']]
If you apply list
func on each item, it would turn each item which is in string format to a list of strings.
>>> [list(i) for i in lst]
[['b', 'a', 'n', 'a', 'n', 'a'], ['m', 'a', 'n', 'g', 'o'], ['a', 'p', 'p', 'l', 'e']]
>>>
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