list.set-nth($list, $n, $value) returns a copy of $list with the element at index $n replaced by $value. Indexes are 1-based. Negative $n counts from the end (-1 is last). Load it with @use "sass:list" on Dart Sass 1.23+. Global alias: set-nth().
Out-of-range indexes error.
Official docs: Sass throws if there is no existing element at $n. Guard with list.length(), or only set after list.index() returns a non-null index.
Official samples.
list.set-nth(10px 20px 30px, 1, 2em) → 2em 20px 30px. list.set-nth(10px 20px 30px, -1, 8em) → 10px 20px 8em. list.set-nth((Helvetica, Arial, sans-serif), 3, Roboto) → Helvetica, Arial, Roboto.
Syntax
Syntax
SCSS
@use "sass:list";
list.set-nth(10px 20px 30px, 1, 2em); // 2em 20px 30px
list.set-nth(10px 20px 30px, -1, 8em); // 10px 20px 8em
list.set-nth((Helvetica, Arial, sans-serif), 3, Roboto);
// Helvetica, Arial, Roboto
// Global alias still works
set-nth(10px 20px 30px, 2, 1rem);
Pattern: find a slot with index or pick a fixed position → rewrite with set-nth → reassign if you need to keep growing the same variable.
Reference
Index Rules
How replacement works:
Idea
Meaning
$n: 1
Replace the first item
$n: -1
Replace the last item
Immutability
Returns a new list; original is unchanged
vs list.nth
nth reads; set-nth writes a copy
Out of range / null
Compile error — guard first
Separator is preserved.
Space lists stay space-separated; comma lists stay comma-separated after the replacement.
Negative indexes replace from the end (-1 = last).
Reassign when applying multiple edits to one variable.
Prefer list.set-nth after @use "sass:list".
One line: when you need to replace the value at a position, call list.set-nth($list, $n, $value).
Practice
Compile Notes
Practical checklist:
checklist.txt
1. @use "sass:list"
2. Remember indexes are 1-based
3. Use -1 to replace the last item
4. Reassign: $list: list.set-nth($list, $n, $val)
5. Guard null indexes from list.index before set-nth
Frequently Asked Questions
list.set-nth($list, $n, $value) returns a copy of $list with the item at index $n replaced by $value. Example: list.set-nth(10px 20px 30px, 1, 2em) is 2em 20px 30px.
No. It returns a new list. The original variable stays the same unless you reassign, for example $list: list.set-nth($list, 2, $val).
Official docs: negative $n counts from the end. list.set-nth(10px 20px 30px, -1, 8em) replaces the last item, yielding 10px 20px 8em.
Sass throws an error if there is no existing element at $n. Check list.length first, or only set after a valid list.index result.
list.nth reads the value at an index. list.set-nth returns a new list with that index replaced.
Built-in modules with @use need Dart Sass 1.23+. LibSass and Ruby Sass do not load sass:list the same way—use the global set-nth() name there if you must.