Reputation: 3
I am leetcoding and implementing a stack when I saw the answer use a pop function using self.items.pop()[0].
def pop(self):
if len(self.items) > 0:
return self.items.pop()[0]
In this case does this simply do the same thing pop() does?
I understand that pop(x) will pop the value at the xth index. I would appreciate some examples of pop()[x].
Upvotes: 0
Views: 625
Reputation: 49
You can try it.
def pop(self):
if len(self.items) > 0:
return self.items[1].pop(0)
Her items[1] is items[items list index]
items = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Upvotes: -1
Reputation: 6740
I'm assuming, based on your phrasing, that self.items
is a list
. The pop
method for lists, as you've pointed out, can be used to remove and return an element of the list at a specified index. If you omit the index, then the last item is removed and returned.
Either way, pop
returns the item that was removed. If you put [0]
after the call to pop
, you'll get the first item of the item that was popped. So, if self.items
is [[1, 2, 3], [4, 5, 6]]
, then self.items.pop()
would be [4, 5, 6]
and therefore self.items.pop()[0]
would be 4
.
Upvotes: 2