SARSA vs Q-Learning Explained: Temporal Difference Learning, with Python Code
SARSA vs Q-learning explained: how temporal difference learning works, why on policy and off policy agents pick different paths, with Python code.

Two robots are learning to cross a field with a cliff along one side. Both are told the same rules, both explore the same way, and both use almost the same code. One learns to walk right along the edge, by the shortest route. The other learns to keep a few steps back. The difference between them is one line, and it is the difference between SARSA and Q-learning.
SARSA vs Q-learning is the classic first comparison in temporal difference learning, the family of methods that lets an agent learn after every single step. This guide explains how temporal difference learning works, what each method learns, why one is called on policy and the other off policy, and when to pick which. A Python example then runs both on the famous cliff walking problem and shows the trade in numbers.
This is the second part of our reinforcement learning series. If you are new to the field, start with reinforcement learning explained, which introduces Q-learning, and our guide to Markov decision processes.
What this guide covers
- SARSA vs Q-learning at a glance
- What is temporal difference learning?
- The TD update in one line
- SARSA: learn from the move you take
- Q-learning: learn from the best move
- On policy vs off policy
- A Python example: cliff walking
- Which one should you use?
- Beyond SARSA and Q-learning
- Frequently asked questions
- Closing thoughts
SARSA vs Q-learning at a glance
| SARSA | Q-learning | |
|---|---|---|
| Learns toward | The value of the next action it will take | The value of the best next action |
| Type | On policy | Off policy |
| What it learns | The value of its own exploring behavior | The value of the greedy, optimal behavior |
| Cliff walking route | Safe route away from the edge, 17 steps | Shortest route along the edge, 13 steps |
| Reward while learning (our demo) | About −28 per episode | About −50 per episode |
| Best for | Costly or risky exploration, such as real robots | Learning the optimal policy, reusing old data, deep RL |
What is temporal difference learning?
An agent that learns from experience has to answer one question again and again: how good is this state, or this action, really? There are two classic ways to find out.
Monte Carlo methods wait until the episode is over. Once the agent reaches the goal, or fails, it adds up all the rewards it got and uses that total to update every state it visited. The answer is honest, but slow: nothing is learned until the end, and a long episode gives a noisy total.
Temporal difference (TD) learning does not wait. After every single step it makes a small correction, using the reward it just got plus its own current guess of how good the next state is. It learns a guess from a guess. This idea, called bootstrapping, was set out by Richard Sutton in 1988, and it is what makes most of reinforcement learning practical.
TD learning has a famous early success. In the early 1990s Gerald Tesauro's TD-Gammon learned backgammon by playing against itself with TD learning, and reached a level close to the best human players. SARSA and Q-learning are the two simplest TD methods for learning which action to take.
The TD update in one line
Every TD method shares the same shape. The agent keeps an estimate, makes a step, and compares:
new estimate = old estimate + alpha * (target - old estimate)
target = reward + gamma * (estimate of what comes next)
The part in brackets is the TD error: how much better or worse the step went than expected. The learning rate alpha sets how big each correction is, and the discount gamma sets how much the future counts. The only real question is what to use as the estimate of what comes next. SARSA and Q-learning give different answers.
SARSA: learn from the move you take
SARSA gets its name from the five things each update uses: the State, the Action taken, the Reward, the next State, and the next Action. It was introduced by Gavin Rummery and Mahesan Niranjan in 1994, and named SARSA later by Richard Sutton.
The key is the last letter. SARSA first chooses its next action, using its usual rule, random moves included. Then it updates toward the value of that chosen action:
target = r + gamma * Q(s2, a2) # a2 = the action SARSA will really take next
If the agent sometimes stumbles in a random direction, those stumbles show up in its targets. SARSA learns how good each action is given the way it really behaves, mistakes and all. Next to a cliff, that means the values near the edge come out low, since a random step there can be a fall.
Q-learning: learn from the best move
Q-learning, from Chris Watkins in 1989, changes one thing. It does not care which action it will take next. It updates toward the best action available at the next state:
target = r + gamma * max over a of Q(s2, a) # the best move, taken or not
Q-learning learns how good each action is if the agent acted perfectly from then on. Its random exploring moves still happen, but they never enter its targets. Next to a cliff, the edge looks fine to Q-learning, since a perfect agent never falls. So it learns the shortest route, along the edge, and keeps falling off it while it explores.
On policy vs off policy
This difference has a name. A policy is the agent's rule for choosing actions. Every learner here has two policies in play: the behavior policy it uses to act, and the target policy whose value it is learning.
- On policy methods, like SARSA, learn the value of the same policy they act with. What they learn matches what they do.
- Off policy methods, like Q-learning, act with one policy and learn about another. Q-learning explores with epsilon greedy moves while learning the value of the purely greedy policy.
Off policy learning is a big deal in practice. It means an agent can learn the best policy from data collected some other way: old episodes, another agent, or a human driving the robot. That is why the deep Q-network, which learned Atari games from pixels, is built on Q-learning and replays stored experience. On policy methods have to learn mostly from data their current policy produced, a theme that comes up again in DAgger and in modern methods such as GRPO.
A Python example: cliff walking
Cliff walking is the standard test for this, from Sutton and Barto's textbook. The world is a 4 by 12 grid. The agent starts at the bottom left and must reach the bottom right. The cells between them along the bottom row are a cliff: stepping into one costs 100 points and sends the agent back to the start. Every other move costs 1 point, so shorter is better.
Both agents use the same learning rate, the same exploration (a random move 10% of the time) and the same 500 episodes. The only difference is the single line that sets the target. We average over 50 runs.
import numpy as np
# Cliff walking (Sutton and Barto, Example 6.6).
# A 4 x 12 grid. The robot starts at the bottom left (S) and must reach the
# bottom right (G). The cells between them along the bottom row are a cliff:
# stepping in costs -100 and sends the robot back to the start. Every other
# move costs -1. Both learners explore the same way (epsilon = 0.1), and the
# only difference between them is ONE line: the value they learn toward.
ROWS, COLS = 4, 12
START, GOAL = (3, 0), (3, 11)
CLIFF = {(3, c) for c in range(1, 11)}
ACTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)] # up, down, left, right
ALPHA, GAMMA, EPS = 0.5, 1.0, 0.1
def step(s, a):
r = min(max(s[0] + ACTIONS[a][0], 0), ROWS - 1)
c = min(max(s[1] + ACTIONS[a][1], 0), COLS - 1)
if (r, c) in CLIFF:
return START, -100.0, False # fell: back to start
return (r, c), -1.0, (r, c) == GOAL
def pick(Q, s, rng):
if rng.random() < EPS:
return int(rng.integers(4)) # explore
q = Q[s]
return int(rng.choice(np.flatnonzero(q == q.max()))) # exploit, ties at random
def run(method, episodes, seed):
rng = np.random.default_rng(seed)
Q = np.zeros((ROWS, COLS, 4))
returns = []
for _ in range(episodes):
s, total, done = START, 0.0, False
a = pick(Q, s, rng)
while not done:
s2, r, done = step(s, a)
a2 = pick(Q, s2, rng)
if method == "SARSA":
target = r + GAMMA * Q[s2][a2] * (not done) # the move it WILL take
else:
target = r + GAMMA * Q[s2].max() * (not done) # the best move, taken or not
Q[s][a] += ALPHA * (target - Q[s][a])
s, a, total = s2, a2, total + r
returns.append(total)
return Q, np.array(returns)
def greedy_path(Q):
s, path = START, [START]
while s != GOAL and len(path) < 60:
s, _, _ = step(s, int(np.argmax(Q[s])))
path.append(s)
return path
print(f"{'method':>12} {'reward per episode (last 100, while exploring)':>48} {'learned path':>14}")
for method in ["SARSA", "Q-learning"]:
runs = [run(method, 500, seed) for seed in range(50)]
online = np.mean([ret[-100:].mean() for _, ret in runs])
length = np.median([len(greedy_path(Q)) - 1 for Q, _ in runs])
print(f"{method:>12} {online:>48.1f} {length:>11.0f} steps")
for method in ["SARSA", "Q-learning"]:
Q, _ = run(method, 500, 0)
route = set(greedy_path(Q))
print(f"\n{method} route (* = path, C = cliff):")
for r in range(ROWS):
print(" ".join("S" if (r, c) == START else "G" if (r, c) == GOAL else
"*" if (r, c) in route else "C" if (r, c) in CLIFF else "."
for c in range(COLS)))
Running it prints:
method reward per episode (last 100, while exploring) learned path
SARSA -27.6 17 steps
Q-learning -50.2 13 steps
SARSA route (* = path, C = cliff):
. . . . * * * * * * * *
. * * * * . . . . . . *
* * . . . . . . . . . *
S C C C C C C C C C C G
Q-learning route (* = path, C = cliff):
. . . . . . . . . . . .
. . . . . . . . . . . .
* * * * * * * * * * * *
S C C C C C C C C C C G

Q-learning finds the optimal route. Its learned path runs right along the cliff edge, 13 steps, the shortest the grid allows. If it stopped exploring and followed that path, it would earn the best possible score of −13.
But it pays for that while learning. With 10% random moves, a step toward the cliff from the edge row is a 100 point fall. Q-learning averages about −50 per episode over the last 100 episodes, close to the textbook figure.
SARSA plays it safe and earns more. Its values count its own random moves, so cells next to the cliff look dangerous. It learns a longer route a row or two away from the edge, 17 steps, and averages about −28 per episode, nearly twice as good as Q-learning while learning.
Neither is wrong. They answer different questions. Q-learning asks what is best if the agent acts perfectly. SARSA asks what is best given how the agent really acts. Sutton and Barto note that if exploration is slowly reduced to zero, both end up on the optimal path.
Which one should you use?
- Exploring is costly or risky: pick SARSA, or another on policy method. A real robot that falls, crashes or breaks things during training should learn values that include its own mistakes.
- You want the optimal policy and can explore safely, as in a simulator: pick Q-learning. It learns the best behavior directly.
- You have old data or data from someone else: pick Q-learning or another off policy method. SARSA cannot make good use of actions it did not choose.
- You plan to scale up with a neural network: Q-learning is the base of the deep Q-network family. Most large on policy methods are policy gradient methods instead, which later parts of this series cover.
For robots, the safety argument has a long reach. The 2026 pattern of starting from demonstrations and then improving with practice, covered in reinforcement learning beyond imitation, exists partly to keep real robots away from costly exploration.
Beyond SARSA and Q-learning
SARSA and Q-learning are the start of a larger family. A few of the next steps:
- Expected SARSA updates toward the average value of the next actions, weighted by how likely each is. It keeps SARSA's caution with less noise, and often beats both.
- Double Q-learning fixes Q-learning's habit of overestimating values, which comes from always taking the maximum of noisy estimates.
- n step methods and TD(lambda) look more than one step ahead before bootstrapping, filling the gap between TD and Monte Carlo.
- Deep Q-networks replace the table with a neural network, so Q-learning can work on camera images and other large inputs.
All of them keep the core idea of temporal difference learning: improve a guess, one step at a time, using the next guess.
Frequently asked questions
What is the difference between SARSA and Q-learning?
Both update a table of action values after every step. SARSA updates toward the value of the action it will really take next, so it learns the value of its own exploring behavior. Q-learning updates toward the best action available next, whether or not it takes it, so it learns the value of the greedy policy.
Is SARSA on policy or off policy?
SARSA is on policy. It learns the value of the same policy it uses to act, including its random exploring moves. Q-learning is off policy: it acts with one policy, such as epsilon greedy, while learning the value of another, the greedy policy.
What is temporal difference learning?
Temporal difference learning is a way to learn values from experience, one step at a time. After each step, the agent compares its old estimate with the reward it got plus its estimate of the next state, and moves the old estimate toward that target. It does not need a model of the world or the end of the episode.
Why does Q-learning do worse than SARSA in cliff walking?
Q-learning learns the shortest route, right along the cliff edge. While it still explores, a random move sometimes pushes it off, costing 100 points. SARSA counts those random moves in its values, so it learns a safer route away from the edge and collects more reward while learning.
Which is better, SARSA or Q-learning?
Neither wins everywhere. Q-learning finds the optimal policy and can learn from any data, so it scales to deep methods like DQN. SARSA is safer while learning, since it plans around its own mistakes, which matters when exploring is costly, as on a real robot.
Closing thoughts
SARSA and Q-learning differ by one line of code, and that line decides what the agent believes. SARSA learns the value of what it really does, so it respects its own mistakes and stays clear of the cliff. Q-learning learns the value of perfect play, so it finds the best route and pays for its exploring along the way.
The same split, on policy against off policy, runs through all of reinforcement learning. It applies to table based methods like these and to the large models that train robots and language models today. Knowing which side a method is on tells you a lot about how it will behave.
If you run the example, try exploring less (epsilon 0.01) or more (0.3), and watch how the gap between the two routes changes. We would like to hear what you find.
References
- R. S. Sutton and A. G. Barto, Reinforcement Learning: An Introduction, 2nd edition, MIT Press, 2018, Section 6.5 and Example 6.6 (cliff walking). incompleteideas.net
- R. S. Sutton, Learning to Predict by the Methods of Temporal Differences, Machine Learning, 1988. springer.com
- G. A. Rummery and M. Niranjan, On-Line Q-Learning Using Connectionist Systems, Cambridge University Engineering Department, 1994.
- C. J. C. H. Watkins and P. Dayan, Q-learning, Machine Learning, 1992. springer.com
- G. Tesauro, Temporal Difference Learning and TD-Gammon, Communications of the ACM, 1995. acm.org