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]
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With