Array functions
Before you explode a list column, check whether a built-in array function already answers the question on the row itself: does the cart contain milk, how many tags are there, which items are in both lists. This lesson shows those functions, and the higher-order ones that change every element in place.
Step 1 · PySpark functions · Silver · Arrays and nested data, lesson 4 of 5
On this page
Show code in
Every code block on the page follows this.
Read first: explode · collect_list / collect_set (skip if you know them)
In plain words first
A shopping bag is a list. You can answer many questions without tipping it out on the floor: "is there milk in it?", "how many things?", "what is in both my bag and yours?". Tipping it out (explodingexplode: Turn each element of an array into a row of its own, copying the other columns. Learn more →) and packing it back (grouping) works, but it is slow and loses empty bags.
Array functions are those questions asked of the bag itself, one row at a time.
Why not explode everything?
Exploding a column of arrays turns one row into many, and answering "does this cart contain milk?" then needs a groupBy to collapse it again: two steps, a 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 →, and empty or nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more → arrays silently disappear along the way. Array functions answer the same question on the row itself.
Run the example
Input: carts
| user | items |
|---|---|
| ana | [milk, eggs, milk, bread] |
| bo | [bread] |
| cy | [] |
| di | null |
from pyspark.sql import functions as F result = carts.select( "user", F.size("items").alias("n_items"), F.array_contains("items", "milk").alias("has_milk"), F.element_at("items", 1).alias("first_item"), F.sort_array(F.array_distinct("items")).alias("unique_sorted"), F.array_join("items", ", ").alias("as_text"), )
SELECT user, size(items) AS n_items, array_contains(items, 'milk') AS has_milk, element_at(items, 1) AS first_item, sort_array(array_distinct(items)) AS unique_sorted, array_join(items, ', ') AS as_text FROM carts
Look at the last two rows. Cy's empty cart has size 0 and no first item. Di's cart is null, and size returns -1 for it in classic Spark (null when ANSI mode is on, the Spark 4.0 default). Filtering with size(items) > 0 handles both.
The toolkit
| Question | Function | Notes |
|---|---|---|
| How many elements? | size(arr) | -1 or null for a null array |
| Contains a value? | array_contains(arr, v) | null if the array is null |
| Element by position | element_at(arr, n), arr[i] | element_at is 1-based and negative n counts from the end; brackets are 0-based |
| Sort | sort_array(arr, asc=False), array_sort | sort_array puts nulls first ascending |
| Remove duplicates | array_distinct(arr) | Keeps first-seen order |
| Into a string | array_join(arr, sep) | Skips nulls unless you pass a replacement |
| Min / max element | array_min, array_max | |
| Part of an array | slice(arr, start, length) | 1-based |
| Position of a value | array_position(arr, v) | 1-based, 0 if absent |
| Flatten nested arrays | flatten(arr_of_arrays) |
Comparing two arrays
| Function | a = [1,2,3], b = [2,3,4] |
|---|---|
| array_union(a, b) | [1, 2, 3, 4] |
| array_intersect(a, b) | [2, 3] |
| array_except(a, b) | [1] |
| arrays_overlap(a, b) | true |
They answer questions such as "which permissions did this user lose?" (array_except(old, new)) without exploding either side. All of them return de-duplicated results.
Higher-order functions
To change every element, Spark has functions that take a lambda and run it inside the JVM, element by element:
carts.select( F.transform("items", lambda x: F.upper(x)).alias("upper_items"), F.filter("items", lambda x: x != "milk").alias("no_milk"), F.exists("items", lambda x: x.startswith("b")).alias("has_b_item"), F.aggregate("prices", F.lit(0.0), lambda acc, x: acc + x).alias("cart_total"), )
SELECT transform(items, x -> upper(x)) AS upper_items, filter(items, x -> x != 'milk') AS no_milk, exists(items, x -> x LIKE 'b%') AS has_b_item, aggregate(prices, 0D, (acc, x) -> acc + x) AS cart_total FROM carts
upper(x)), which the JVM then evaluates for every element. That is why it is as fast as any built-in, unlike a Python UDFUDF: User-defined function: your own Python function applied to each row. Flexible but much slower than built-in functions. Learn more →. The in-browser engine does not run higher-order functions yet, so this example is read-only.Common mistakes
- Exploding just to filter or count — array_contains and size work in place, with no extra rows and no shuffle.
- Mixing up 0-based and 1-based indexes — arr[0] and element_at(arr, 1) are the same element.
- Treating size(null) as 0 — It is -1 (or null in ANSI mode). Handle null arrays explicitly.
- Writing a Python UDF to map over an array — transform does it natively and much faster.
Key takeaways
- Use array functions in place instead of explode + groupBy.
- element_at and slice are 1-based; brackets are 0-based.
- array_union, array_intersect and array_except compare arrays directly.
- transform, filter and aggregate run lambdas in the JVM, as fast as built-ins.
Interview prep
THE QUESTION
"Each user has an array of roles in two snapshots. Find users who lost the admin role."
array_contains(old.roles, "admin") & ~array_contains(new.roles, "admin"), or compute array_except(old.roles, new.roles) to list every lost role. No explode is needed. Mention the null-array case: a user missing from the new snapshot needs a left join and coalesce to an empty array.Avoid: exploding both arrays and joining. Array functions answer membership questions without changing the row count.
Follow-ups · answer out loud, then open
Follow-up"How do you check that two arrays share at least one element?"
F.arrays_overlap(a, b). It returns true, false, or null when there is no common non-null element but either array contains a null.Scenario"Keep only the elements of an array greater than 10, and double them."
F.transform(F.filter("xs", lambda x: x > 10), lambda x: x * 2). They run inside the JVM, with no explode and no UDF.Trap"size() of a null array is 0."
spark.sql.legacy.sizeOfNull is true and ANSI mode is off, the Spark 3 default. With ANSI on, the Spark 4.0 default, it returns null. Check for null explicitly rather than relying on either.Check yourself
3 questionsWhat is element_at(array("a","b","c"), -1)?
Show the answer
"c". A negative index counts from the end.
Which returns the elements of a that are not in b?
Show the answer
array_except(a, b). array_except is set difference.
Why is F.transform faster than a Python UDF doing the same thing?
Show the answer
The lambda becomes a Spark expression evaluated in the JVM. No rows are sent to a Python process.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Arrays and nested data · lesson 5 of 5 · 6 min readJSON and structs
Parse JSON strings with from_json, reach into nested fields, and flatten structs.
Related lessons
Previous: collect_list / collect_set
Primary sources: Collection functions · functions.transform