How to use list as stack in Python

List is a compound data type in Python, used to group together other values. Lists might contain items of different data types.

The methods available with list make it very easy to use as a stack, where the last element added is the first retrieved. To retrieve an item from the top of stack, use append(). To retrieve an item from the top of the stack, use pop() without any explicit index. Lets understand it with an example.

Create a sample list
    

stack_demo = [1, 5, 6, 7, 8, 9]

    
    
Add Item to stack
    
        
stack_demo.append(10)
print(stack_demo)

# Output
[1, 5, 6, 7, 8, 9, 10]


Retrieve top element from stack
    

top_element = stack_demo.pop()
print(top_element)
print(stack_demo)

# Output 
10
[1, 5, 6, 7, 8, 9]

    
    

Follow US on Twitter: