Home > OS >  How do I create lists in a list in Python? Is it possible?
How do I create lists in a list in Python? Is it possible?

Time:12-16

How to make list each character of list? like this:

li = ['A','B','C']

into :

li = [['A'],['B'],['C']]

CodePudding user response:

See "list comprehension".

It is simply,

[[i] for i in i]

or more generally,

[f(x) for x in list_name]

CodePudding user response:

To transform a list of elements into a list of lists, each containing one element, you can use a list comprehension:

li = ['A', 'B', 'C']
new_li = [[x] for x in li]
print(new_li)  # Output: [['A'], ['B'], ['C']]

Alternatively, you can use a for loop:

new_li = []
for x in li:
    new_li.append([x])
print(new_li)  # Output: [['A'], ['B'], ['C']]

Both approaches will create a new list with the same elements as li, but each element will be wrapped in a single-element list.

  • Related