Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Formulating a nested list comprising elements in the same position from another nested list

How can I take a nested list and re-formulate it into a new nested list in which:

  • the first list of the new nested list, B, comprises the first element of all of the lists within the nested list A.
  • the second list of the new nested list, B, comprises the second element of all of the lists within the nested list A.
  • the nth list of the new nested list, B, comprises the nth element of all of the lists within the nested list A.

Examples are:

A = [[100,200,300], [400,500,600], [1000,1500,300]]

such that B becomes:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

B = [[100,400,1000], [200,500,1500], [300,600,300]]

Of course, in reality A contains hundreds of lists not just three. So i need a method to automate this for large numbers of lists.

>Solution :

If you are sure that all the inner lists have the same length, then

B = [[inner_list[i] for inner_list in A] for i in range(len(A))]

Otherwise you can additionnaly check if index i is not out of bounds for current inner list:

B = [
    [inner_list[i] if i < len(inner_list) else None for inner_list in A]
    for i in range(len(A))
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading