collect_list / collect_set
Sometimes you want the opposite of explode: all of a customer's products in one list, all the pages a user visited in one session. collect_list and collect_set build those arrays per group. This lesson shows both, why the order of the list is not guaranteed, and why collecting can run out of memory.
Step 1 · PySpark functions · Silver · Arrays and nested data, lesson 3 of 5
On this page
Show code in
Every code block on the page follows this.
Read first: groupBy + agg (skip if you know it)
In plain words first
At the end of a shopping day, you gather all of one customer's receipts and staple them into a single bundle. A list keeps every receipt, even repeats; a set keeps each distinct item once. Either way the bundle has to fit in one hand, which is why collecting a huge group can fail.
What it does
It is the reverse of explodeexplode: Turn each element of an array into a row of its own, copying the other columns. Learn more →: many rows in, one arrayarray: A column that holds a list of values in each row, such as the items of one order. Learn more → per group out.
Step by step
visits
| user | page |
|---|---|
| u1 | home |
| u1 | search |
| u1 | home |
| u2 | cart |
| u2 | nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more → |
Output
| user | pages | distinct_pages |
|---|---|---|
| u1 | [home, search, home] | [home, search] |
| u2 | [cart] | [cart] |
The null page for u2 is skipped by both. collect_set drops the second "home".
Run the example
Input: visits
| user | ts | page |
|---|---|---|
| u1 | 10:00 | home |
| u1 | 10:02 | search |
| u1 | 10:05 | home |
| u2 | 11:00 | cart |
| u2 | 11:03 | null |
from pyspark.sql import functions as F result = (visits.groupBy("user").agg( F.collect_list("page").alias("pages"), F.collect_set("page").alias("distinct_pages"), F.size(F.collect_set("page")).alias("n_distinct"), ))
SELECT user, collect_list(page) AS pages, collect_set(page) AS distinct_pages, size(collect_set(page)) AS n_distinct FROM visits GROUP BY user
Getting a reliable order
collect_list adds values in whatever order rows reach the aggregationaggregate: A function that turns many rows into one value per group: count, sum, avg, min, max. Learn more →, which depends on partitioning and shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → timing. Sorting the DataFrameDataFrame: A table of rows and named columns that Spark processes in parallel. It never changes: every operation returns a new one. Learn more → first does not fix that, because the groupBy shuffle reorders rows. Two reliable options:
- Collect structsstruct: A column that holds a small record with named fields, like an address with a city and a pin code. Learn more → whose first field is the sort key, then sort the array:
F.sort_array(F.collect_list(F.struct("ts", "page"))), and take.pagefrom the result. Structs sort by their fields in order. - Use a window ordered by time with a full framewindow frame: The rows around the current one that a window function looks at, such as "the previous 6 rows" or "the last 7 days". Learn more →, and
collect_listover it, then deduplicate to one row per group.
array_agg, the SQL-standard name for collect_list, in recent versions. It has the same ordering caveat; the struct-and-sort trick works everywhere.Under the hood: memory Optional deep dive
Most aggregations shrink data before the shuffle: a sum is one number per group. collect_list cannot; the partial result is the whole list. Every value is shuffled, and the complete array for a group must fit in one tasktask: The work for one partition in one stage, run on one CPU core. Learn more →'s memory. A single user with 50 million events produces one 50-million-element array and, often, an out-of-memory error. Collect only what you need, cap it with slice, or rethink whether you need the array at all.
Common mistakes
- Relying on collect_list order — Sort explicitly with structs and sort_array.
- Sorting before groupBy and expecting it to stick — The shuffle destroys that order.
- Collecting huge groups — Skewedskew: When one key has far more rows than the others, so one task does most of the work while the rest wait. Learn more → keys produce giant arrays and OOM errors.
Key takeaways
- collect_list keeps duplicates; collect_set removes them. Both skip nulls.
- Neither guarantees order, even after an orderBy.
- Collect structs and sort_array them for a deterministic order.
- Collecting shuffles every value and holds each group's array in memory.
Interview prep
THE QUESTION
"Build each user's page path in time order."
sort_array(collect_list(struct(ts, page))), then extract the page field, with a note that a plain collect_list after orderBy is not guaranteed to be ordered. Bonus: warn about users with millions of events and suggest limiting to a session or a time range.Avoid: orderBy then groupBy with collect_list, assuming the order survives. The shuffle does not preserve it.
Follow-ups · answer out loud, then open
Follow-up"Do collect_list and collect_set keep nulls?"
Scenario"Some users have millions of events. collect_list per user fails with out-of-memory. What do you do?"
Trap"collect_list is cheap because it is just an aggregation."
Check yourself
3 questionsHow do you get a guaranteed time-ordered list of pages per user?
Show the answer
sort_array(collect_list(struct("ts", "page"))). Structs sort by their first field, so sorting the collected structs orders by ts. A prior orderBy is lost in the shuffle.
A group has values a, b, null, a. What does collect_set return (in some order)?
Show the answer
[a, b]. collect_set removes duplicates and both collect functions skip nulls.
Why is collect_list risky on skewed data?
Show the answer
The full array of a huge group must fit in one task's memory. Partial aggregation cannot shrink a list, so a hot key builds one enormous array.
Practise this
Problems that use collect_list / collect_set, graded on hidden tests
Keep going
Up next · Arrays and nested data · lesson 4 of 5 · 4 min readArray functions
array_contains, size, element_at, sort_array and the set functions, without exploding.
Related lessons
explodePySpark functions · 4 min read
groupBy + aggSpark internals · 8 min read
Data skew and salting
Previous: posexplode
Primary sources: functions.collect_list · functions.collect_set