the problems related to the following code segment, initializing an empty list and append

Question:

I write a program, including the following function, which involves initializing an empty list, and append it during iterations.

def build_window_sequence(x,y,windowsize):
    num_sequence = x.shape[0]
    num_size = x.shape[1]
    x_window_sequence = []
    y_window = []
    for i in range(num_sequence):
        low_index = 0
        high_index = 0
        for j in range(num_size):
            low_index = j
            high_index = low_index+windowsize-1
            current_index = low_index+round(windowsize/2)
            x_window_sequence = x_window_sequence.append(train_x[i,low_index:high_index])
            y_window = y_window.append('train_y[current_index]')
    return x_window, y_window

However, running the program gives the following error message

x_window_sequence = x_window_sequence.append('train_x[i,low_index:high_index]')
AttributeError: 'NoneType' object has no attribute 'append'

Just for more information, the involved arrays have the following shape

train_x shape (5000, 501)
train_y shape  (5000, 501)
Asked By: user297850

||

Answers:

x_window_sequence = x_window_sequence.append(train_x[i,low_index:high_index])

Here you are assigning the result of .append, but .append does not return anything (that is, it returns None). You can read more here.

Answered By: Colin Ricardo

list.append is an in place operation which returns None.

Therefore, you should append without assigning back to a variable:

x_window_sequence.append(train_x[i,low_index:high_index])
y_window.append('train_y[current_index]')

This is noted explicitly in the Python documentation.

Answered By: jpp
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.