0

Let's say I got the following array:

array = [[1, 2, 3, 1],
         [4, 5, 6, 4],
         [7, 8, 9, 7], 
         [7, 8, 9, 7]]

I want to remove the first and last list in the array and than the first and last element of the middle lists (return should basically be: [[5, 6], [8, 9]]).

I tried the following:

array.remove(array[0])
array.remove(array[-1])
for i in array:
     array.remove(i[0])
     array.remove(i[-1])

But I always get ValueError: list.remove(x): x not in list. Why?

4 Answers 4

1

You should remove the items from the sublist, not the parent list:

for i in array:
    i.remove(i[0])
    i.remove(i[-1])

You can also remove both items in one line using del:

>>> for i in array:
...    del i[0], i[-1]
>>> array
[[5, 6], [8, 9]]
Sign up to request clarification or add additional context in comments.

2 Comments

That's what I was looking for, so stupid. Thanks a lot!
@MickeyMahoney If it helped you may consider accepting :)
1

Using numpy

import numpy as np

array = np.array(array)
array[1:3, 1:3]

return

array([[5, 6],
       [8, 9]])

Comments

1

Simple way to achive this is to slice the array list using list comprehension expression like:

array = [[1, 2, 3, 1],
         [4, 5, 6, 4],
         [7, 8, 9, 7],
         [7, 8, 9, 7]]

array = [a[1:-1]for a in array[1:-1]]

Final value hold by array will be:

[[5, 6], [8, 9]]

Here array[1:-1] returns the list skipping the first and last element from the array list

1 Comment

Keep in mind that a list comprehension creates a new list instead of mutating the original as in OP's case
0

Or, with <list>.pop:

array = [[1, 2, 3, 1],
         [4, 5, 6, 4],
         [7, 8, 9, 7], 
         [7, 8, 9, 7]]

for i in range(len(array)): # range(len(<list>)) converts 'i' to the list inedx number.
    array[i].pop(0)
    array[i].pop(-1)

To answer your question,

.remove removes the first matching value, not a specific index. Where as .pop removes the it by the index.

Hope this helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.