liveBook · Manning

Stack

As explained in Get Programming: Learn to code with Python

A data structure in which elements are added and removed from the same end, so the most recently added element is removed first.

A stack adds and removes elements at the same end. The last element added is the first removed, so a stack is first-in, last-out. section 26.4

Picture a stack of pancakes: put new pancakes on top and take pancakes from the top. With a Python list, the end of the list acts as the top; append() adds an element and pop() removes it. section 26.4

Listing 32.1. Definition for the Stack class
class Stack(object):
    def __init__( self):
        self.stack = []                   #1
    def get_stack_elements(self):
        return self.stack.copy()          #2
    def add_one(self , item):
        self.stack.append(item)           #3
    def add_many(self , item, n):
        for i in range(n):                #4
            self.stack.append(item)       #4
    def remove_one(self):
        self.stack.pop()                  #5
    def remove_many(self , n):
        for i in range(n):                #6
            self.stack.pop()              #6
    def size(self):
        return len(self.stack)            #7
    def prettyprint(self):
        for thing in self.stack[::-1]:    #8
            print('|_',thing, '_|')       #8

A Stack class packages list-backed operations such as adding and removing one or several items. section 32.1

Pancakes and circles

Add blueberry and chocolate pancakes, then remove one to take the most recently added pancake. The same Stack class can also hold Circle objects. section 26.4 section 32.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines a list-backed Stack class and demonstrates its methods with strings and objects.
Examples
Uses pancake flavors and Circle objects to demonstrate adding, removing, and storing items.
What it assumes
Assumes familiarity with lists and creating Python classes before defining a Stack object.
What you can do after
Build it from scratch with a Python class that stores items in a list and provides stack operations.
How it connects
Connects stacks to lists, classes, object types, and queues.

Also explained in

Compare how 14 books explain stack →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.