Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list into list of lists

Tags:

python

list

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))
like image 502
Sameer Avatar asked Jul 27 '16 05:07

Sameer


People also ask

How to convert list to list of lists in Python?

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’.

How to convert a list that contains multiple lists into one?

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.

Why can’t I convert a list of tuples to a list?

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.

How do you iterate through a list of lists in Python?

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


1 Answers

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']]
>>> 
like image 174
Avinash Raj Avatar answered Sep 22 '22 19:09

Avinash Raj