Stacks question

I am learning stacks for the first time. Below is the solution and URL
The question I have is this. The line “self.top_item = None”. self.top_item seems to be an instance of class Node, but why is it not written like “self.top_item = Node(value)” with value set to default of None?
Even though it is written “self.top_item = None”, below it has the attribute of class Node, “self.top_item.get_value()”. How is this so?

from node import Node

# Add your Stack class below:
class Stack:
  def __init__(self):
    self.top_item = None
  def peek(self):
    return self.top_item.get_value()

You must elect a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

you’re creating an empty stack

how many nodes are there in an empty stack?

if that number is 0, then how many nodes would you create?

Ok, you are saying it is because it is an empty stack of nodes. But then how does it have the attribute “.get_value()” of class Node?

if you have no values then you have no values

and no it’s not a stack of nodes, the nodes are your stack. you are using a linked list
you don’t put nodes in a stack, you are using nodes to represent a stack

I’m going to keep saying it:
most questions you can possibly have are things you can answer by considering the concept itself and ignoring code

a stack supports push and pop.

you push by adding a value to the front of the list (because the front is where your implementation supports adding and removing)

you pop by looking at and removing the first value

for a python list:

stack = []
print(stack.pop())  # 4
print(stack.pop())  # 3

for python’s list you’d instead work with the back, since that’s where that data structure supports adding and removing