Manuel Medina
Manuel Medina

Reputation: 409

How to .pop() a specific item on a 2D list?

How to .pop() a specific item on a 2D list? Let's say I have the list:

fruit_list = [['tomato', 'pineapple', 'mango'], ['cherry', 'orange', 'strawberry']]

If I .pop() fruit_list it would return ['cherry', 'orange', 'strawberry'], because that is the last item of list but is there a way in Python to just pop 'mango', the last item of an inner list?

Upvotes: 1

Views: 5775

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1125318

You need to call .pop() on the inner list then:

fruit_list[0].pop()

Your outer fruit_list contains more list objects. If you want to pop an item from one of those lists, call .pop() directly on such a list.

A quick demo:

>>> fruit_list = [['tomato', 'pineapple', 'mango'], ['cherry', 'orange', 'strawberry']]
>>> fruit_list[0]
['tomato', 'pineapple', 'mango']
>>> fruit_list[0].pop()
'mango'
>>> fruit_list
[['tomato', 'pineapple'], ['cherry', 'orange', 'strawberry']]

Upvotes: 0

user2555451
user2555451

Reputation:

Use this:

item = fruit_list[0].pop()

See a demonstration below:

>>> fruit_list = [['tomato', 'pineapple', 'mango'], ['cherry', 'orange', 'strawberry']]
>>> fruit_list[0]
['tomato', 'pineapple', 'mango']
>>> fruit_list[0].pop()
'mango'
>>> fruit_list
[['tomato', 'pineapple'], ['cherry', 'orange', 'strawberry']]
>>>

Notice how you first index fruit_list at 0 to get the inner list. Then, you call .pop on that.

Upvotes: 3

Related Questions