Eliscpe - 1 year ago 97

Python Question

how would I remove the brackets and place the coordinates into x and y from a list in python?

Example:

if i input

`([(2,1),(3,1),(4,2)])`

It would return

`for x: 2,3,4 and for y: 1,1,2`

Answer Source

You can use `zip`

with `*`

:

```
a = ([(2,1),(3,1),(4,2)]) # ie, a list of x,y pairs
x, y = zip(*a) # x = (2, 3, 4) and y = (1, 1, 2),
```

This is basically two steps in one line. The first is that `zip`

changes `[(2,1),(3,1),(4,2)]`

into `((2, 3, 4), (1, 1, 2))`

(which is the step of the similar question). Then this tuple, which is now a pair of tuples, is unwrapped into `x`

and `y`

.

This specific idiom, of unzipping a list of (x,y) pairs into a pair of lists of x and y data, is so common and useful that I'm leaving it posted even though there's an answer to a previous question that only does the unzip.