From the course: Programming Foundations: Data Structures
Unlock this course with a free trial
Join today to access over 25,300 courses taught by industry experts.
Use a list as a stack in Python - Python Tutorial
From the course: Programming Foundations: Data Structures
Use a list as a stack in Python
- [Instructor] Some programming languages provide built-in stack functionality, but in others, you may need to implement your own stack using the available tools. A stack is essentially an ordered list, but with a restricted way of adding and removing items. You can only add a remove from the top. In Python we can use a list to act as a stack and mimic this behavior. To create a stack of cards, we'll start with an empty list. Each element will represent a card, and the first card added will be at the bottom of the deck. We'll use the append method to add cards to the top. The top of the stack will be the back of the list, and the bottom of the stack will be the front of the list. Each card will be represented as a string, but you could also create a custom structure or a class to hold the card data. Let's add the jack of hearts, two of diamonds and ten of spades. Here we have the jack of hearts on the bottom of the stack and the ten of spades on the top. Technically, since this is a…