> For the complete documentation index, see [llms.txt](https://pyohamen.gitbook.io/til/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://pyohamen.gitbook.io/til/algorithm/data_structure/stack.md).

# Stack

> Structure with limited access to data.
>
> L.I.F.O. ( Last In First Out ) Structure

## How it works?

* You keep putting elements on top
* You have easy access to remove or look at the top element

![](/files/-MSZw11YJIKEGvG123B-)

## When to use?

* when you only care about the most recent elements
* the order in which you see & save elements actually matters

## Push & Pop

1. Push

   : when you add an element to a stack

   -> O(1)
2. Pop

   : when you taken an element off of the stack

   -> O(1)

   \=> All you need here is to look at the top element of the stack!

## Stack in Python

* `pop()` is a given function
* `append()` is equivalent to a push function

Make your own code instead of using `append()` since it traverses the whole list, taking O(n)

-> it will take a lot faster if we push/pop from the first element in a linked list!


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://pyohamen.gitbook.io/til/algorithm/data_structure/stack.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
