# The stack

Bitcoin Script runs on a stack: items go on top and operations take them off. Watch a simple script execute step by step with an animated diagram.

Canonical page: https://mybitcoinexplorer.com/learn/the-stack
Topic: Bitcoin Script
Published: 2026-10-29
Updated: 2026-10-30


## Last in, first out
A stack is like a pile of plates: you can only add to or take from the top.

> Diagram: Running `2 3 OP_ADD 5 OP_EQUAL`, one step at a time — 2:2;3:2,3;OP_ADD:5;5:5,5;OP_EQUAL:TRUE

1. Push 2.
1. Push 3. The stack is [2, 3].
1. `OP_ADD` pops 3 and 2, pushes 5.
1. Push 5. The stack is [5, 5].
1. `OP_EQUAL` pops both, pushes TRUE because they're equal.

The script ends with TRUE on top, so it succeeds.

## Why a stack?
It's simple to implement correctly, uses very little memory, and every step is easy to reason about. That simplicity matters when thousands of independent nodes must agree exactly.

## Limits
- At most 1,000 items on the stack at once.
- Pushed items are at most 520 bytes (outside Taproot script paths).
- Scripts and opcode counts have size limits too.


## Practise on paper
### Worked example: Run this script yourself
Script: `3 4 OP_ADD 7 OP_EQUAL`
1. Push 3 → [3]
1. Push 4 → [3, 4]
1. OP_ADD → [7]
1. Push 7 → [7, 7]
1. OP_EQUAL → [TRUE]
Ends with TRUE, so it succeeds.


## Two stacks, actually
Script also has an "alt stack" for temporarily setting items aside (`OP_TOALTSTACK`, `OP_FROMALTSTACK`). Standard payment scripts rarely use it.


## Key takeaways

- Script uses a last-in, first-out stack.
- Data is pushed; opcodes pop, compute and push.
- A script succeeds if it ends with a true value on top.

## Common questions

### What counts as true?

Any non-zero value. Zero, an empty item or negative zero is false.

### Can a script fail early?

Yes. Opcodes like OP_VERIFY stop execution immediately if their check fails.

### Why does Bitcoin use a stack instead of variables?

A stack machine is simple to implement identically across many independent nodes, which matters for consensus.

### What happens if a script fails?

The transaction is invalid and nodes reject it.

## Related lessons

- [Bitcoin Script](https://mybitcoinexplorer.com/learn/bitcoin-script)
- [Script opcodes](https://mybitcoinexplorer.com/learn/opcodes)
- [Pay to public key hash (P2PKH)](https://mybitcoinexplorer.com/learn/p2pkh)
- [Pay to public key (P2PK)](https://mybitcoinexplorer.com/learn/p2pk)
