Stack

Declare stack

We can declare stack with no initial data, or with a starting position.

stack = deque()
stack = deque([start_index, end_index])
stack = deque(some_list)

.peek() = deque[-1]

Normally before you pop it like from a stack, you need to peek at the value. In Python, we just do deque[-1]

pop()

If using it as a stack, pop() removes the topmost element stored in the stack But if you are using it as queue, use popleft()

append((whatever elements in a list))

Unlike list, deque’s append is different. In list, we do .append([list of elements]) but in deque, we don’t use the square brackets but instead use circular brackets. If you are adding a tuple like (dx,dy) and an int like cost to deque, we do

deque.append(((x,y),cost))

list(stack)

When using deque() in the form of stack and when we want to return that stack in list form, we simply convert it via list()

stack =deque()
return list(stack)

’‘.join(stack)

I thought it would be 4324 but no.

stack = deque([3, 2, 3, 4])
result = ''.join(stack)
print(result)
# 3242

Practice questions