Search code examples
pythonlistpython-2.7list-manipulation

Obtaining the first and second "column's" from a pair of lists


I have many pairs of lists of variable lengths (5,4,6 pairs etc..) inside a single big list, lets call it LIST. Here are two lists among the many inside the big LIST as an example:

[(38.621833, -10.825707),
 (38.572191, -10.84311),      -----> LIST[0]
 (38.580202, -10.860877),
 (38.610917, -10.85217),
 (38.631526, -10.839338)]

[(38.28152, -10.744559),
 (38.246368, -10.744552),     -----> LIST[1]
 (38.246358, -10.779088),
 (38.281515, -10.779096)]

I need to create two seperate variables lets say, of which one variable will have the first "column" (i.e. LIST[0][0][0], LIST[0][1][0] AND SO ON) of all the pairs of the lists(i.e. 38.621833, 38.572191 etc) and the second variable will have the second "column" (i.e. LIST[0][0][1], LIST[0][1][1] AND SO ON) of all the pairs of the lists.

So finally I will have two variables (say x,y) that will contain all the values of the first and second "columns" of all the lists in the LIST.

The problem I face is that all these lists are not of the same length!!

I tried

x = []
y = []
for i in range(len(LIST)):
    x.append(LIST[i][0][0]) #append all the values of the first numbers 
    y.append(LIST[i][1][1]) #append all the values of the second numbers

What I expect:

x = (38.621833,38.572191,38.580202,38.610917,38.631526,38.28152,38.246368,38.246358,38.281515)

y = (-10.825707,-10.84311,-10.860877,-10.85217,-10.839338,-10.744559,-10.744552,-10.779088,-10.779096)

But here because of the variable pairs, my loop stops abrubptly in between. I know I need to also change the LIST[i][j][0] here, and j changes with each list. But because of the different pairs, I don't know how to go about.

How do I go about doing this?


Solution

  • I would use two simple for loops (it's also generic for LIST being longer than 2):

    x=[]
    y=[]
    for i in range(len(LIST)):
        for j in LIST[i]:
            x.append(j[0])
            y.append(j[1])