How to create list of items in a list by index in python


I have a list m:

m = ['ABC', 'XYZ', 'LMN']

and I want output as follows:

m = [['a','x','l']
     ['b','y','m']
     ['c','z','n']]

How can this be done?


Answer

Use list(zip(*..)) to transpose the nested list, and use list comprehension to create nested list:

print(list(zip(*[list(i.lower()) for i in m])))

Output:

[('a', 'x', 'l'), ('b', 'y', 'm'), ('c', 'z', 'n')]

If want sub-values to be lists:

print(list(map(list,zip(*[list(i.lower()) for i in m]))))

Output:

[['a', 'x', 'l'], ['b', 'y', 'm'], ['c', 'z', 'n']]