Range
| Description: | Describes a range of values from a starting value to an ending value, with an optional stride. |
| Annotation: | range |
| Literal Syntax: | <start_value>..<end_value> or <start_value>..<second_value>..<end_value>. E.g., 1..10. |
| Casts: | seq |
| See also: | Types of Data - Ranges |
Additional Language Notes
Ranges are inclusive by default.
Examples:
- Values from 1 to 5 inclusive:
1..5 # => ╭───┬───╮ # => │ 0 │ 1 │ # => │ 1 │ 2 │ # => │ 2 │ 3 │ # => │ 3 │ 4 │ # => │ 4 │ 5 │ # => ╰───┴───╯In many programming languages, the step (or interval) is specified. Nushell's range is inspired by more functional languages, where the second value is literally the second value that should be generated. The step is then automatically calculated as the distance between the first and second values.
Example - Values from 1 to 10, striding with 2 (only odds):
1..3..10 # => ╭───┬───╮ # => │ 0 │ 1 │ # => │ 1 │ 3 │ # => │ 2 │ 5 │ # => │ 3 │ 7 │ # => │ 4 │ 9 │ # => ╰───┴───╯Exclusive range - You can also use
..<to have values up to, but not including, the range end.Values from 1 to 5 (exclusive):
1..<5 # => ╭───┬───╮ # => │ 0 │ 1 │ # => │ 1 │ 2 │ # => │ 2 │ 3 │ # => │ 3 │ 4 │ # => ╰───┴───╯Range values can be floats:
(1.0)..(1.2)..(2.2) # => ╭───┬──────╮ # => │ 0 │ 1.00 │ # => │ 1 │ 1.20 │ # => │ 2 │ 1.40 │ # => │ 3 │ 1.60 │ # => │ 4 │ 1.80 │ # => │ 5 │ 2.00 │ # => │ 6 │ 2.20 │ # => ╰───┴──────╯Note: Parentheses (subexpressions) are not required in this example; they are simply used for readability.
When no second value is given, the step is
1(or-1when counting down). The exception is a float range whose start and end are less than1apart. Its step is based on the order of magnitude of the difference:0.1..0.3 # => ╭───┬──────╮ # => │ 0 │ 0.10 │ # => │ 1 │ 0.20 │ # => │ 2 │ 0.30 │ # => ╰───┴──────╯Ranges can also work backward:
5..1 # => ╭───┬───╮ # => │ 0 │ 5 │ # => │ 1 │ 4 │ # => │ 2 │ 3 │ # => │ 3 │ 2 │ # => │ 4 │ 1 │ # => ╰───┴───╯The start value is optional. The default start value is
0.(..5) == (0..5) # => trueThe end value is also optional. The default end value is infinite, so
1..is an infinite range starting at 1:1.. | describe # => rangeNote: If you enter
1..by itself at the prompt, Nushell starts listing its values. Interrupt the generation using Ctrl+C.Ranges are lazy, meaning they do not generate their values until needed. You can use a range with no specified end point and combine it with a command that takes only the first n elements. For example, you could generate the numbers from 1 to 5 using:
1.. | take 5 # => ╭───┬───╮ # => │ 0 │ 1 │ # => │ 1 │ 2 │ # => │ 2 │ 3 │ # => │ 3 │ 4 │ # => │ 4 │ 5 │ # => ╰───┴───╯Conversion - A range may be converted to a
listusing:1..5 | each {||} | describe # => list<int> (stream)A range stays a
rangewhen it is assigned to a variable or passed throughcollect. Most filter commands, such aseach,takeandappend, produce a list from it.