Search code examples
pythonlistnestednested-loopsnested-lists

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:

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))
    ]