Nanor
Nanor

Reputation: 2550

Lists in Python becoming very complex

I have a simple function which takes a 2D list as a parameter:

def get_noise_estimate(imag_array):
    temp = []

    temp.append(imag_array[:20])
    temp.append(imag_array[-20:])

In an example instance, it has 305 elements, each with 129 elements. I like to think of this has 305 columns each with 129 rows. I found out these things using my debugger:

>>> len(imag_array)
305

>>> len(imag_array[0])
129

When I get the first 20 and last 20 'columns' of the array and append it to temp I get the following:

>>> len(temp)
2
>>> len(temp[0])
20
>>> len(temp[1])
20
>>> len(temp[0][0])
129

My temp list has become quite confusing. I'd like len(temp) to equal 40 rather than 2 blocks of 20. To illustrate what I mean I'll show how I might do something similar in Java:

int[] temp = new int[40];

for(int i = 0; i < 20; i++){
    temp[i] = imag_array[i];
}

for(int i = 0; i < 20; i++){
   temp[i+20] = imag_array[imag_array.length-i]
}

The above is off the top of my head but I hope it makes clear what I'm getting at.

Upvotes: 2

Views: 105

Answers (2)

Joel
Joel

Reputation: 23827

Change:

temp.append(imag_array[:20])
temp.append(imag_array[-20:])

to

temp.extend(imag_array[:20])
temp.extend(imag_array[-20:])

The append command adds something as the last element of temp. So it's making the first element of temp be the list imag_array[:20]. extend takes all the elements of the list in the argument and adds each to the end of the list.

(and note Jay's answer: temp = imag_array[:20]+imag_array[-20:] is actually cleaner - it doesn't require predefining temp and avoids using .append)

Upvotes: 7

Jay
Jay

Reputation: 9582

temp = imag_array[:20] + imag_array[-20:]

Upvotes: 3

Related Questions