1

If I have a 2D array like:

array = [["hello"], [1,2,3], [4,5,6]]

How can I get the program to remove the first sub array so that it turns out like this:

array = [[1,2,3], [4,5,6]]

If I try to do array[0].pop[0], the array ends up like this:

array = [[], [1,2,3], [4,5,6]]

5 Answers 5

3

You must do

array.pop(0)

Since you want to remove the first element

Sign up to request clarification or add additional context in comments.

Comments

2

When you do array[0].pop(0) you are removing "hello" not ["hello"] Since ["hello"] is at position 0 of array you should use

array.pop(0)

Comments

0

You are deleting the first item of the first sub list, not whole of the sub list. You can use del statement to delete the first item:

>>> array=[["hello"],[1,2,3],[4,5,6]]
>>> 
>>> del array[0]
>>> 
>>> array
[[1, 2, 3], [4, 5, 6]]

Or if you want to preserve the deleted item you can use array.pop(0).

Comments

0

array[0] is the list ["hello"], the first (and only) item in this list is the string "hello", so if you pop it you get the empty list [], hence you get your result.

As mentioned the right way to pop the first list from array is array.pop(0)

Comments

0

To remove the first item from array and return it use array.pop(0):

>>> array = [["hello"], [1,2,3], [4,5,6]]
>>> array.pop(0)
['hello']
>>> array
[[1, 2, 3], [4, 5, 6]]

If you're not interested in the return value, you can use slice assignment or del. These can be used to remove more than one item.

>>> array = [["hello"], [1,2,3], [4,5,6]]
>>> array[:1] = []
>>> array
[[1, 2, 3], [4, 5, 6]]

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.