AI Hints
LangGraph · Lesson 20 of 120

Appending Lists

Operator.add.

⏱ 2 min read▶ Video at 20:45🎓 Free
Watch this lesson in the LangGraph courseWatch on YouTube ↗Full LangGraph course

With a reducer, a node doesn't need to read the old list, and add to it. It just returns the new items. That makes nodes simpler, and safer, especially when several nodes write to the same key.

Appending Lists
From the video: Appending Lists
  • Return only new items
  • Simpler nodes
  • Safer with many writers

A basket that adds up

The basket is a list with operator add, and the total is a number with operator add. Each node returns only its own book, and its own price. Run it. The basket collects all three books, and the total adds up all three prices, without any node reading the old values.

basket.pypython
import operator
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, START, END

class Basket(TypedDict):
    items: Annotated[list[str], operator.add]
    total: Annotated[float, operator.add]

def add_dune(s):  return {"items": ["Dune"], "total": 9.99}
def add_emma(s):  return {"items": ["Emma"], "total": 7.99}
def add_circe(s): return {"items": ["Circe"], "total": 10.99}

b = StateGraph(Basket)
b.add_sequence([add_dune, add_emma, add_circe])
b.add_edge(START, "add_dune"); b.add_edge("add_circe", END)
out = b.compile().invoke({"items": [], "total": 0})
print(out["items"], round(out["total"], 2))
Output
['Dune', 'Emma', 'Circe'] 28.97

Starting values

With a reducer, the input is the starting value. Pass an empty list, or zero, when you invoke. And remember, updates add up even across loops, so a loop that returns the same item each time will add it each time.

keyvalue
Inputthe starting value
Listsstart with []
Numbersstart with 0
Loopsadd every time

Summary

With operator add, nodes return only new items, and the reducer combines them. Lists join, and numbers sum. Next, writing your own reducer.

Key takeaways
  • Return new items only
  • Lists join
  • Numbers sum
Next up: Custom Reducers — your own rules