0
0
SASSmarkup~5 mins

Built-in list functions in SASS

Choose your learning style9 modes available
Introduction

Built-in list functions help you work with groups of values easily. They save time and make your code cleaner.

When you want to get the length of a list of colors.
When you need to add a new item to an existing list of sizes.
When you want to check if a value is inside a list of fonts.
When you want to join two lists of margins into one.
When you want to get the first or last item from a list of padding values.
Syntax
SASS
@function list-function-name($list, $optional-arguments) {
  // Use built-in list functions like length(), nth(), append(), join(), index()
}

List functions work with lists written like: (red, green, blue) or red, green, blue.

Use parentheses for clarity, but Sass also understands space or comma separated lists.

Examples
This gets the number of items in the list $colors, which is 3.
SASS
$colors: (red, green, blue);
$length: length($colors);
This gets the first item from the list $sizes, which is 10px.
SASS
$sizes: 10px 20px 30px;
$first-size: nth($sizes, 1);
This adds Verdana to the end of the $fonts list.
SASS
$fonts: (Arial, Helvetica);
$new-fonts: append($fonts, Verdana);
This joins two lists into one: (1, 2, 3, 4).
SASS
$list1: (1, 2);
$list2: (3, 4);
$joined: join($list1, $list2);
Sample Program

This Sass code shows how to use built-in list functions to get the length, get an item, add an item, and join lists. The @debug lines print the results in the console.

SASS
@use 'sass:list';

$colors: (red, green, blue);

// Get length of list
$color-count: list.length($colors);

// Get first color
$first-color: list.nth($colors, 1);

// Add a new color
$updated-colors: list.append($colors, purple);

// Join two lists
$more-colors: (yellow, orange);
$all-colors: list.join($updated-colors, $more-colors);

// Output results
@debug 'Number of colors: #{$color-count}';
@debug 'First color: #{$first-color}';
@debug 'Colors after append: #{inspect($updated-colors)}';
@debug 'All colors joined: #{inspect($all-colors)}';
OutputSuccess
Important Notes

Time complexity: List functions run quickly because lists are simple arrays.

Space complexity: Functions like append() and join() create new lists, so they use extra memory.

Common mistake: Forgetting that list indexes start at 1, not 0.

Use append() to add items, but use join() to combine two lists.

Summary

Built-in list functions make working with groups of values easy and clean.

Remember list indexes start at 1 in Sass.

Use functions like length(), nth(), append(), and join() to manage lists.