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]
5 Answers 5
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.
1 Comment
zip
solution is very neat.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.
Comments
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 = []
Comments
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])
Comments
You can do:
x = [i[0] for i in list]
y = [i[1] for i in list]