Search code examples
pythonpython-zip

Creating a list with zip()


I'm trying to understand why when my code look like this:

x_coord = [23, 53, 2, -12, 95, 103, 14, -5]
y_coord = [677, 233, 405, 433, 905, 376, 432, 445]
z_coord = [4, 16, -6, -42, 3, -6, 23, -1]
labels = ["F", "J", "A", "Q", "Y", "B", "W", "X"]
points=[]
for point in zip(labels, x_coord,y_coord, z_coord):
    points = points.append(point)

I get the error:

AttributeError: 'NoneType' object has no attribute 'append'

But when I do this:

x_coord = [23, 53, 2, -12, 95, 103, 14, -5]
y_coord = [677, 233, 405, 433, 905, 376, 432, 445]
z_coord = [4, 16, -6, -42, 3, -6, 23, -1]
labels = ["F", "J", "A", "Q", "Y", "B", "W", "X"]
points=[]
for point in zip(labels, x_coord,y_coord, z_coord):
    points.append(point)

It works , theres is something wrong with the syntaxis? , I mean points is define as a list and list has the append method.


Solution

  • This is because points.append(point) is a method and doesn't return a value, hence when you do points = points.append(point), points takes the (lack of a) return value and becomes None (you overwrote the list type with None type).

    However, when you do point.append(point), you are correctly adding elements to the list by calling its built-in method, and not overwriting anything, which is why the second code works but not the first.