0

What I'm trying to do is to put each index 0 of each item of list a in the list x and each index 1 of each item of list a in the list y. When the plot is shown, it only appears one point. Does anybody know what am I doing wrong? Thanks in advance.

a = [[1,2], [2,3], [3,4], [5,6], [6,7]]

for item in a:
    x = [ ]
    y = [ ]
    x.append(item[0])
    y.append(item[1])


plt.plot(x, y, 'ro')
plt.axis([-50, 50, -50, 50])
plt.show()
1
  • In each loop iteration you set x and y to an empty list. Move x = [] and y = [] out of the for loop. Commented Dec 9, 2013 at 19:46

2 Answers 2

1

You overwrite the values of x and y every time through the loop, so only the last point is stored. Move your declaration of x and y outside of your loop.

It makes more sense to take advantage of Python's list comprehensions though:

x, y = ([p for p,q in a], [q for p,q in a])
plt.plot(x, y, 'ro')
plt.axis([-50, 50, -50, 50])
plt.show()

List comprehension:

([p for p,q in a], [q for p,q in a])

this piece of code returns a 2-tuple whose elements are two Python lists. The lists are formed using a list comphrehension which takes each list of x,y and splits the xs into the first returned list, and the ys into the second.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok. Thanks a lot! :) Can you explain a little more about list comprehensions?
1

Try this:

x, y = zip(*a)

It is compact and readable and it should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.