f.ashouri
f.ashouri

Reputation: 5667

Extract x and y values from a list

I have list like this:

pp=[[0,0] , [-1,5], [2,3], [1,5], [3,6], [4,5], [5,3], [8,-2], [4, -4], [2, -5]]

And I want to extract x and y values in separate lists like:

ppx= [0, -1, 2, 1, 3, 4, 5, 8, 4, 2]

Upvotes: 7

Views: 8860

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121674

Use zip() to separate the coordinates:

ppx, ppy = zip(*pp)

This produces tuples; these are easily enough mapped to list objects:

ppx, ppy = map(list, zip(*pp))

This works in both Python 2 and 3 (where the map() iterator is expanded for the tuple assignment).

Demo:

>>> pp=[[0,0] , [-1,5], [2,3], [1,5], [3,6], [4,5], [5,3], [8,-2], [4, -4], [2, -5]]
>>> ppx, ppy = zip(*pp)
>>> ppx
(0, -1, 2, 1, 3, 4, 5, 8, 4, 2)
>>> ppy
(0, 5, 3, 5, 6, 5, 3, -2, -4, -5)
>>> ppx, ppy = map(list, zip(*pp))
>>> ppx
[0, -1, 2, 1, 3, 4, 5, 8, 4, 2]
>>> ppy
[0, 5, 3, 5, 6, 5, 3, -2, -4, -5]

Upvotes: 10

elParaguayo
elParaguayo

Reputation: 1318

Use list comprehensions:

pp=[[0,0] , [-1,5], [2,3], [1,5], [3,6], [4,5], [5,3], [8,-2], [4, -4], [2, -5]]
ppx=[a[0] for a in pp]
ppy=[a[1] for a in pp]

More on list comprehensions in the Python docs: http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

Upvotes: 1

Nigel Tufnel
Nigel Tufnel

Reputation: 11524

I think that list comprehensions is the most straightforward way:

xs = [p[0] for p in pp]
ys = [p[1] for p in pp]

Upvotes: 11

Related Questions