-2

I've made a list of tuples (each represents a 2D point), and then I want to plot it by using pyplot. So my problem is that I can't get only x coordinats by slicing the list. Here is the code I'm using

points = [(1,2), (3,4), (5,6)]
plt.plot(points[:][0], points[:][1], 'o')

If I'd like to print

in:  print(points[:][0])
out: (1, 2)

Do you have any idea how to get list of first tuples element?

petezurich
  • 9,280
  • 9
  • 43
  • 57
Legolando
  • 168
  • 1
  • 10
  • 3
    Possible duplicate of [Transpose/Unzip Function (inverse of zip)?](https://stackoverflow.com/questions/19339/transpose-unzip-function-inverse-of-zip) – buran Dec 11 '18 at 21:03
  • This can be found here: https://stackoverflow.com/questions/12142133/how-to-get-first-element-in-a-list-of-tuples – Xion Dec 11 '18 at 21:03
  • 3
    Literally: get the first element of each tuple: `[x for x, y in points]`, and similarly for `y`. – ForceBru Dec 11 '18 at 21:04
  • @ForceBru works like charm, thank you for your help. – Legolando Dec 11 '18 at 21:14
  • 1
    @Legolando, you're welcome! Of course, that's a bit too repetitive, and you can also get a pair of nice tuples like this: `X, Y = zip(*points)`. – ForceBru Dec 11 '18 at 21:16

2 Answers2

1

Solution by @ForceBru

points = [(1,2), (3,4), (5,6)]
x = [p[0] for p in points]
y = [p[1] for p in points]

Or much easier way (x, y are now tuples)

x, y = zip(*points)
Legolando
  • 168
  • 1
  • 10
0

All you need to do, is a comprehension list like this one:

points = [(1,2), (3,4), (5,6)]
x_coordinats = [x[0] for x in points]
y_coordinats = [y[0] for y in points]
Koukou
  • 187
  • 8