Home > Net >  How do I convert the elements of nested lists into separate lists?
How do I convert the elements of nested lists into separate lists?

Time:05-19

say I have a list of lists;

my_list = [['apple', 'banana', 'orange'], ['carrot', 'pumpkin', 'potato']]

Is there a way that I can convert each element in each separate list into its own list?

Output:

new_list = [[['apple'], ['banana'], ['orange']], [['carrot'], ['pumpkin'], ['potato']]]

CodePudding user response:

Yes, you can use a list comprehension to wrap each string in its own list:

[[[item] for item in sublist] for sublist in my_list]

This outputs:

[[['apple'], ['banana'], ['orange']], [['carrot'], ['pumpkin'], ['potato']]]
  • Related