9

You have a 2-Dimensional list of numbers like:

x = [[1,2],[3,4],[5,6],[7,8],[9,10],[11,12],[13,14],[15,16],[17,18]]

You need to split it into two lists in such a way that you get the numbers from the first column in one list and the second column in another list:

[1,3,5,7,9,11,13,15,17] [2,4,6,8,10,12,14,16,18]

How can that be done in python?

I am posting this question because I could not find a simple answer to it. I will be answering it later.

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
aabb bbaa
  • 195
  • 1
  • 3
  • 14

3 Answers3

14

It is the ideal case of using zip as:

>>> x = [[1,2],[3,4],[5,6],[7,8],[9,10],[11,12],[13,14],[15,16],[17,18]]

#       v unpack `x` list
>>> zip(*x)
[(1, 3, 5, 7, 9, 11, 13, 15, 17), (2, 4, 6, 8, 10, 12, 14, 16, 18)]

Returned value is a list of two tuples. In order to save each tuple in variable, you may do:

>>> a, b = zip(*x)
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
2
x_1 = [i[0] for i in x]
x_2 = [i[1] for i in x]
aabb bbaa
  • 195
  • 1
  • 3
  • 14
1
In [27]: x = [[1,2],[3,4],[5,6],[7,8],[9,10],[11,12],[13,14],[15,16],[17,18]]

In [28]: first, second = zip(*x)

In [29]: first
Out[29]: (1, 3, 5, 7, 9, 11, 13, 15, 17)

In [30]: second
Out[30]: (2, 4, 6, 8, 10, 12, 14, 16, 18)
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241