Reputation: 47
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]]
Upvotes: 1
Views: 8982
Reputation: 149776
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]]
Upvotes: 0
Reputation: 8464
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)
Upvotes: 0
Reputation: 2496
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)
Upvotes: 2
Reputation: 11476
You must do
array.pop(0)
Since you want to remove the first element
Upvotes: 3
Reputation: 107287
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)
.
Upvotes: 0