# Extracting a coordinate from a python list of tuples

## Question:

I have a python list

``````training_data=[(x_1, y_1), (x_2, y_2), ..., (x_n, y_n)]
``````

and I wish to extract a list of `x` values

``````training_data_x=[x_1, x_2, ..., x_n]
``````

I have tried

``````for j in range(0, len(training_data)):
training_data_x=[i for i in training_data[j][0]]
``````

and

``````training_data_x=[i for i in training_data[j][0] for j in range(0, len(training_data))]
``````

but neither worked. How can I do this?

A comprehension would do:

``````training_data_x = [x[0] for x in training_data]
``````

I prefer a list comprehension with a self-documenting tuple unpacking:

``````[x for x,y in training_data]
``````

Complete program:

``````training_data=[(1.5, 11), (2.5, 22), (7.5, 77)]
training_data_x = [x for x,y in training_data]
print(training_data_x)
``````

Looks like you just have a list of tuples. I’m still a bit new to python, but I would try :

training_data_x =[]
for i in training_data:
training_data_x.append(i[0])

another way you could do is create a function that takes tuple and returns the x. Then map the function to your training_data_x variable.

# You should unpack them rather than iterating over:

Here is the code:

training_data_x, training_data_y = list(list(zip(*training_data))[0]), list(list(zip(*training_data))[1])

Here is the walkthrough:

1. training_data gets unpacked and a zip object is created.
2. the "list(zip(..))" creates a list with x and y coordinates inside separate tuples something like [(x. coordinates), (y. Coordinates)]
3. Using indexing you extract x and y coordinates (as tuples)
4. use list to convert x and y tuples into separate lists.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.