5

I have a list of lists in the form:

list = [[3, 1], [3, 2], [3, 3]]

And I want to split it into two lists, one with the x values of each sublist and one with the y values of each sublist.

I currently have this:

x = y = []
for sublist in list:
 x.append(sublist[0])
 y.append(sublist[1])

But that returns this, and I don't know why:

x = [3, 1, 3, 2, 3, 3]
y = [3, 1, 3, 2, 3, 3]
Sukrit Kalra
34.6k7 gold badges73 silver badges71 bronze badges
asked Jul 22, 2013 at 19:16

5 Answers 5

11

By doing x = y = [] you are creating x and y and referencing them to the same list, hence the erroneous output. (The Object IDs are same below)

>>> x = y = []
>>> id(x)
43842656
>>> id(y)
43842656

If you fix that, you get the correct result.

>>> x = []
>>> y = []
>>> for sublist in lst:
 x.append(sublist[0])
 y.append(sublist[1])
>>> x
[3, 3, 3]
>>> y
[1, 2, 3]

Although, this could be made pretty easier by doing.

x,y = zip(*lst)

P.S. - Please don't use list as a variable name, it shadows the builtin.

answered Jul 22, 2013 at 19:18

1 Comment

The zip solution is very neat.
4

When you say x = y = [], you're causing x and y to be a reference to the same list. So when you edit one, you edit the other. There is a good explanation here about how references work.

Therefore you can use your code if you say instead

x = []; y = []

You also might want to try zip:

lst = [[3, 1], [3, 2], [3, 3]]
x,y = zip(*lst)

And as Sukrit says, don't use list as a variable name (or int or str or what have you) because though it is a Python built-in (load up an interpreter and type help(list) - the fact that something pops up means Python has pre-defined list to mean something) Python will cheerfully let you redefine (a.k.a. shadow) it. Which can break your code later.

answered Jul 22, 2013 at 19:18

Comments

2

That's because when you construct x and y like x = y = [] then x and y point to the same list. If you want to make them different lists, you should declare them like

x = []
y = []
answered Jul 22, 2013 at 19:19

Comments

1

You are setting x = y = [] meaning x is pointing to y which is pointing to the list so whenever you append to one, you are appending to the other. Change the code to something like this:

x = [] 
y = []
for sublist in list:
 x.append(sublist[0])
 y.append(sublist[1])
answered Jul 22, 2013 at 19:19

Comments

0

You can do:

x = [i[0] for i in list]
y = [i[1] for i in list]
answered Jul 22, 2013 at 19:25

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.