Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append an element of a sublist in python

Tags:

python

list

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]
like image 949
Brady Avatar asked Jul 22 '13 19:07

Brady


2 Answers

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.

like image 125
Sukrit Kalra Avatar answered Sep 26 '22 19:09

Sukrit Kalra


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.

like image 29
A.Wan Avatar answered Sep 24 '22 19:09

A.Wan