Search code examples
pythonlistindexingtuplesenumerate

Python: Initializing and filling a list of lists from another list of lists


I have a list of lists in Python which contains a tuple For eg.

tuple_list = 
[ [(a1,b1), (a2,b2).......(a99, b99)]
  [(c1,d1), (c2,d2).......(c99, d99)]
  .
  .
  .
  [(y1,z1), (y2,z2).......(y99, z99)]]

I want to initialize two list of lists a_list and b_list

In a_list, I want it to have first index of every tuple from tuple_list

a_list = 
 [ [a1, a2.......a99]
      [c1, c2.......c99]
      .
      .
      .
      [y1, y2.......y99]]

and b_list must have second index of every tuple from tuple_list

 [ [b1, b2.......b99]
      [d1, d2.......d99]
      .
      .
      .
      [z1, z2.......z99]]

I tried this

a_list = [[]] * len(tuple_list )
    b_list = [[]] * len(tuple_list )

 for index, list in enumerate(tuple_list ):
        for index2,number in enumerate(list):
            a_list [index].append(number[0])
            b_list [index].append(number[1])

But its giving me some different answer. How do I do it?


Solution

  • You can build a_list and b_list using list comprehnsion like this

    a_list = [[t[0] for t in row] for row in tuple_list]
    b_list = [[t[1] for t in row] for row in tuple_list]