Home > Blockchain >  how to convert the type of each element in a list to a list in python
how to convert the type of each element in a list to a list in python

Time:11-28

How can I change the list below :

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

to this :

list1 = [['A'],['B'],['C']] I don't want to do this manually because elements are too many.

CodePudding user response:

Iterate on the list and wraph each item in a list itself

list1 = ['A', 'B', 'C']
list1 = [[i] for i in list1]
print(list1)  # [['A'], ['B'], ['C']]

CodePudding user response:

new_list = []
for i in list1:
    new_list.append([i])

Should do the trick, but there are other ways.

CodePudding user response:

The most pythonic way to do it in my opinion is:

list1 = ['A', 'B', 'C']
list1 = list(map(lambda e: [e], list1))
print(list1)  # [['A'], ['B'], ['C']]
  • Related