Nushell
Get Nu!
Getting Started
  • The Nushell Book
  • Command Reference
  • Cookbook
  • Language Reference Guide
  • Contributing Guide
Blog
  • English
  • 中文
  • Deutsch
  • Français
  • Español
  • 日本語
  • Português do Brasil
  • Русский язык
  • 한국어
GitHub
Get Nu!
Getting Started
  • The Nushell Book
  • Command Reference
  • Cookbook
  • Language Reference Guide
  • Contributing Guide
Blog
  • English
  • 中文
  • Deutsch
  • Français
  • Español
  • 日本語
  • Português do Brasil
  • Русский язык
  • 한국어
GitHub
  • Introduction
  • Installation
    • Default Shell
  • Getting Started
    • Quick Tour
    • Moving Around the System
    • Thinking in Nu
    • Nushell Cheat Sheet
  • Nu Fundamentals
    • Types of Data
    • Loading Data
    • Data Formats
    • Working with SQLite
    • Pipelines
    • Working with Strings
    • Regular Expressions
    • Working with Binary Data
    • Working with Lists
    • Working with Records
    • Working with Numbers
    • Working with Tables
    • Working with Paths
    • Navigating and Accessing Structured Data
    • Special Variables
  • Programming in Nu
    • Custom Commands
    • Aliases
    • Operators
    • Variables
    • Control Flow
    • Scripts
    • Modules
      • Using Modules
      • Creating Modules
    • Overlays
    • Sorting
    • Testing your Nushell Code
    • Debugging Scripts
    • Language Server
    • Best Practices
  • Nu as a Shell
    • Configuration
    • Configuration Reference
    • Environment
    • Stdout, Stderr, and Exit Codes
    • Working with the Terminal
    • Running System (External) Commands
    • How to Configure 3rd Party Prompts
    • Directory Stack
    • Reedline, Nu's Line Editor
    • Custom Completions
    • Externs
    • Coloring and Theming in Nu
    • Hooks
    • Background Jobs
  • Coming to Nu
    • Coming from Bash
    • Coming from CMD.EXE
    • Coming from PowerShell
    • Nu map from other shells and domain specific languages
    • Nu Map from Imperative Languages
    • Nu Map from Functional Languages
    • Nushell operator map
  • Design Notes
    • How Nushell Code Gets Run
  • (Not So) Advanced
    • Standard Library
      • std/assert
      • std/bench
      • std/clip
      • std/config
      • std/dt
      • std/formats
      • std/help
      • std/input
      • std/iter
      • std/log
      • std/math
      • std/random
      • std/util
      • std/xml
      • std-rfc
    • Dataframes
      • Dataframe Operations
      • Column Selectors
      • Math Expressions
      • String Expressions
      • Dates and Times in Dataframes
      • Masks and Conditionals
      • Aggregations and Window Functions
    • Metadata
    • Creating Your Own Errors
    • Parallelism
    • Plugins
    • explore
    • Building TUIs with tui
    • MCP Server

Working with Lists

Tips

Lists are equivalent to the individual columns of tables. You can think of a list as essentially being a "one-column table" (with no column name). Thus, any command which operates on a column also operates on a list. For instance, where can be used with lists:

[bell book candle] | where ($it =~ 'b')
# => ╭───┬──────╮
# => │ 0 │ bell │
# => │ 1 │ book │
# => ╰───┴──────╯

Creating lists

A list is an ordered collection of values. A list is created using square brackets surrounding values separated by spaces, linebreaks, and/or commas. For example, [foo bar baz] or [foo, bar, baz].

Tips

Nushell lists are similar to JSON arrays. The same [ "Item1", "Item2", "Item3" ] that represents a JSON array can also be used to create a Nushell list.

Lists of numbers with seq

seq generates numbers. With two numbers it counts from the first to the second by 1. With three, the middle one is the increment. Both ends are included when the count lands on them:

seq 1 5 | to nuon
# => [1, 2, 3, 4, 5]
seq 10 -3 1 | to nuon
# => [10, 7, 4, 1]

Counting down needs a negative increment, so seq 5 1 gives an empty list. A single number gives a list that holds only that number, unlike the Unix seq, which counts up to it. An increment of 0 is an error, and so is calling seq with no numbers. With more than three numbers, the first is the start, the second the increment and the last the end, and the ones in between are ignored.

If any of the numbers is a float, every value is a float. Each value is computed as the start plus a multiple of the increment, so rounding errors don't add up, but a float end can still be missed by a hair:

seq 0.1 0.1 0.3 | to nuon
# => [0.1, 0.2]
seq 1 3 | each { $in / 10 } | to nuon
# => [0.1, 0.2, 0.3]

seq returns a stream, so the numbers are made only as they are read, and seq 1 1_000_000_000 | first 3 returns at once. A range such as 1..5 covers many of the same uses, but it is a range value, not a list, and some commands, such as window, every and shuffle, accept only a list. seq gives them one. For letters and dates, use seq char and seq date.

Updating lists

We can insert values into lists as they flow through the pipeline, for example let's insert the value 10 into the middle of a list:

[1, 2, 3, 4] | insert 2 10
# => ╭───┬────╮
# => │ 0 │  1 │
# => │ 1 │  2 │
# => │ 2 │ 10 │
# => │ 3 │  3 │
# => │ 4 │  4 │
# => ╰───┴────╯

We can also use update to replace the 2nd element with the value 10.

[1, 2, 3, 4] | update 1 10
# => ╭───┬────╮
# => │ 0 │  1 │
# => │ 1 │ 10 │
# => │ 2 │  3 │
# => │ 3 │  4 │
# => ╰───┴────╯

Removing or Adding Items from List

In addition to insert and update, we also have prepend and append. These let you insert to the beginning of a list or at the end of the list, respectively.

For example:

let colors = [yellow green]
let colors = ($colors | prepend red)
let colors = ($colors | append purple)
let colors = ($colors ++ ["blue"])
let colors = (["black"] ++ $colors)
$colors
# => ╭───┬────────╮
# => │ 0 │ black  │
# => │ 1 │ red    │
# => │ 2 │ yellow │
# => │ 3 │ green  │
# => │ 4 │ purple │
# => │ 5 │ blue   │
# => ╰───┴────────╯

append also accepts several values at once:

[yellow green] | append purple blue
# => ╭───┬────────╮
# => │ 0 │ yellow │
# => │ 1 │ green  │
# => │ 2 │ purple │
# => │ 3 │ blue   │
# => ╰───┴────────╯

A list given to append or prepend is unwrapped, so its items are added one by one, the same as ++. To add the list as a single item, put it inside another list:

let extra = [purple blue]
[yellow green] | append [$extra]
# => ╭───┬────────────────╮
# => │ 0 │ yellow         │
# => │ 1 │ green          │
# => │ 2 │ [list 2 items] │
# => ╰───┴────────────────╯

Adding and changing data in the Language Guide covers ranges and input that isn't a list.

In case you want to remove items from list, there are many ways. skip allows you skip first rows from input, while drop allows you to skip specific numbered rows from end of list.

let colors = [red yellow green purple]
let colors = ($colors | skip 1)
let colors = ($colors | drop 2)
$colors
# => ╭───┬────────╮
# => │ 0 │ yellow │
# => ╰───┴────────╯

We also have last and first which allow you to take from the end or beginning of the list, respectively.

let colors = [red yellow green purple black magenta]
let colors = ($colors | last 3)
$colors
# => ╭───┬─────────╮
# => │ 0 │ purple  │
# => │ 1 │ black   │
# => │ 2 │ magenta │
# => ╰───┴─────────╯

And from the beginning of a list,

let colors = [yellow green purple]
let colors = ($colors | first 2)
$colors
# => ╭───┬────────╮
# => │ 0 │ yellow │
# => │ 1 │ green  │
# => ╰───┴────────╯

To take or skip items based on a condition rather than a count, use take while, take until, skip while, or skip until. Like where, these accept either a closure or a row condition, where $it is the current item:

let scores = [7 10 8 6 7]
$scores | take while $it > 6
# => ╭───┬────╮
# => │ 0 │  7 │
# => │ 1 │ 10 │
# => │ 2 │  8 │
# => ╰───┴────╯
$scores | skip until $it < 7
# => ╭───┬───╮
# => │ 0 │ 6 │
# => │ 1 │ 7 │
# => ╰───┴───╯

Using the Spread Operator

To append one or more lists together, optionally with values interspersed in between, you can also use the spread operator (...):

let x = [1 2]
[
  ...$x
  3
  ...(4..7 | take 2)
]
# => ╭───┬───╮
# => │ 0 │ 1 │
# => │ 1 │ 2 │
# => │ 2 │ 3 │
# => │ 3 │ 4 │
# => │ 4 │ 5 │
# => ╰───┴───╯

Iterating over Lists

To iterate over the items in a list, use the each command with a closure of Nu code that specifies what to do to each item. The closure parameter (e.g. |elt| in { |elt| print $elt }) is the current list item, but the enumerate filter can be used to provide index and item values if needed. For example:

let names = [Mark Tami Amanda Jeremy]
$names | each { |elt| $"Hello, ($elt)!" }
# Outputs "Hello, Mark!" and three more similar lines.

$names | enumerate | each { |elt| $"($elt.index + 1) - ($elt.item)" }
# Outputs "1 - Mark", "2 - Tami", etc.

The where command can be used to create a subset of a list, effectively filtering the list based on a condition.

The following example gets all the colors whose names end in "e".

let colors = [red orange yellow green blue purple]
$colors | where ($it | str ends-with 'e')
# The condition passed to `where` must evaluate to a boolean.
# This outputs the list [orange blue purple].

In this example, we keep only values higher than 7.

let scores = [7 10 8 6 7]
$scores | where $it > 7 # [10 8]

The reduce command computes a single value from a list. It uses a closure which takes 2 parameters: the current item (conventionally named elt) and an accumulator (conventionally named acc). To specify an initial value for the accumulator, use the --fold (-f) flag. To change elt to have index and item values, use the enumerate filter. For example:

let scores = [3 8 4]
$"total = ($scores | reduce { |elt, acc| $acc + $elt })" # total = 15

$"total = ($scores | math sum)" # easier approach, same result

$"product = ($scores | reduce --fold 1 { |elt, acc| $acc * $elt })" # product = 96

$scores | enumerate | reduce --fold 0 { |elt, acc| $acc + $elt.index * $elt.item } # 0*3 + 1*8 + 2*4 = 16

Summarizing and comparing lists in the Language Guide explains how reduce starts with and without --fold, which lists math sum and math avg accept, and the rules for the other commands in this chapter.

Accessing the List

Note

The following is a basic overview. For a more in-depth discussion of this topic, see the chapter, Navigating and Accessing Structured Data.

To access a list item at a given index, use the $name.index form where $name is a variable that holds a list.

For example, the second element in the list below can be accessed with $names.1.

let names = [Mark Tami Amanda Jeremy]
$names.1 # gives Tami

If the index is in some variable $index we can use the get command to extract the item from the list.

let names = [Mark Tami Amanda Jeremy]
let index = 1
$names | get $index # gives Tami

The length command returns the number of items in a list. For example, [red green blue] | length outputs 3.

The is-empty command determines whether a string, list, or table is empty. It can be used with lists as follows:

let colors = [red green blue]
$colors | is-empty # false

let colors = []
$colors | is-empty # true

The in and not-in operators are used to test whether a value is in a list. For example:

let colors = [red green blue]
'blue' in $colors # true
'yellow' in $colors # false
'gold' not-in $colors # true

The any command determines if any item in a list matches a given condition. For example:

let colors = [red green blue]
# Do any color names end with "e"?
$colors | any {|elt| $elt | str ends-with "e" } # true

# Is the length of any color name less than 3?
$colors | any {|elt| ($elt | str length) < 3 } # false

let scores = [3 8 4]
# Are any scores greater than 7?
$scores | any {|elt| $elt > 7 } # true

# Are any scores odd?
$scores | any {|elt| $elt mod 2 == 1 } # true

The all command determines if every item in a list matches a given condition. For example:

let colors = [red green blue]
# Do all color names end with "e"?
$colors | all {|elt| $elt | str ends-with "e" } # false

# Is the length of all color names greater than or equal to 3?
$colors | all {|elt| ($elt | str length) >= 3 } # true

let scores = [3 8 4]
# Are all scores greater than 7?
$scores | all {|elt| $elt > 7 } # false

# Are all scores even?
$scores | all {|elt| $elt mod 2 == 0 } # false

Like where, both any and all also accept a row condition in place of a closure, using $it for the current item:

let scores = [3 8 4]
$scores | any $it > 7 # true
$scores | all $it > 2 # true

Both stop at the first item that decides the answer. See all and any for empty input and other edge cases.

Set Operations and Combinations

The union, intersect, and difference commands treat lists as sets. Their results contain no duplicates, and items stay in the order in which they first appear:

let a = [1 2 3 4]
let b = [3 4 5 6]
$a | union $b
# => ╭───┬───╮
# => │ 0 │ 1 │
# => │ 1 │ 2 │
# => │ 2 │ 3 │
# => │ 3 │ 4 │
# => │ 4 │ 5 │
# => │ 5 │ 6 │
# => ╰───┴───╯
$a | intersect $b
# => ╭───┬───╮
# => │ 0 │ 3 │
# => │ 1 │ 4 │
# => ╰───┴───╯
$a | difference $b
# => ╭───┬───╮
# => │ 0 │ 1 │
# => │ 1 │ 2 │
# => ╰───┴───╯

Items match only when they are the same type and value, so 1 and 1.0 are different. For tables, whole rows are compared.

combinations returns every way to choose a given number of items from a list, and permutations returns every ordering of a list. Both return a list of lists, so the examples below join each inner list into a string:

[red green blue] | combinations 2 | each { str join "+" }
# => ╭───┬────────────╮
# => │ 0 │ red+green  │
# => │ 1 │ red+blue   │
# => │ 2 │ green+blue │
# => ╰───┴────────────╯
[a b c] | permutations | each { str join }
# => ╭───┬─────╮
# => │ 0 │ abc │
# => │ 1 │ bac │
# => │ 2 │ cab │
# => │ 3 │ acb │
# => │ 4 │ bca │
# => │ 5 │ cba │
# => ╰───┴─────╯

See chunks, combinations and permutations for tables and edge cases.

Converting the List

The flatten command creates a new list from an existing list by adding items in nested lists to the top-level list. This can be called multiple times to flatten lists nested at any depth. For example:

[1 [2 3] 4 [5 6]] | flatten # [1 2 3 4 5 6]

[[1 2] [3 [4 5 [6 7 8]]]] | flatten | flatten | flatten # [1 2 3 4 5 6 7 8]

On a table, flatten expands a column of lists into one row per item and lifts the fields of a record column into the row. See Reshaping in the Language Guide for --all, column arguments and name clashes.

The wrap command converts a list or a range to a table. Each list value will be converted to a separate row with a single column. A single value that isn't a list becomes a one-field record:

let zones = [UTC CET Europe/Moscow Asia/Yekaterinburg]

# Show world clock for selected time zones
$zones | wrap 'Zone' | upsert Time {|row| (date now | date to-timezone $row.Zone | format date '%Y.%m.%d %H:%M')}
Edit this page on GitHub
Contributors: R. Mark Volkmann, JT, Anton Patrushev, Reilly Wood, jntrnr, rgwood, fdncred, Justin Ma, chtenb, f2hafner, morzel85, Stefan Holderbach, Zhora Trush, zephaniahong, Leon, Joel Afriyie, Hofer-Julian, David Matos, Alpha Chen, Máté FARKAS, Mate Farkas, Ifthel, Connor Sullivan, Sam Vente, amtoine, KAAtheWiseGit, Joerg Schuetter, NotTheDr01ds, Bruce Weirdan, 0x4D5352, joshuanussbaum, 132ikl
Prev
Working with Binary Data
Next
Working with Records