logo

Programming Languages - Ranges

Last Updated: 2024-01-21

C++

Since C++20.

  • Ranges = iterable sequences. An abstraction. Requires begin() and end().
    • Containers = ranges owning their elements. E.g. std::vector
    • Views = lightweight objects that indirectly represent ranges. View do not own the underlying data.

Go

The range form of the for loop iterates over a slice or map.

When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.

for i, v := range []int{1, 2, 4, 8, 16, 32, 64, 128} {
  fmt.Printf("%d, %d\n", i, v)
}

// This returns the index, NOT the value:
for i := range pow {
  // ...
}

// The right way to get values:
for _, value := range pow {
  // ...
}

JavaScript

No built-in ranges, but can use array index to get a sequence:

> Array.from(new Array(5), (x, i) => i)
[0, 1, 2, 3, 4]

Python

In Python, range() is a function to create a sequence.

Syntax: range(start, stop, step).

  • start: optional, default 0.
  • stop: required, exclusive.
  • step: optional, default 1.
>>> [n for n in range(1, 10, 2)]
[1, 3, 5, 7, 9]

Kotlin

for (i in 1..10) print(i)       // inclusive
for (i in 1 until 10) print(i)  // exclusive
for (i in 1..10 step 2) print(i)
for (i in 10 downTo 1) print(i)

Rust

1..2;   // std::ops::Range
3..;    // std::ops::RangeFrom
..4;    // std::ops::RangeTo
..;     // std::ops::RangeFull
5..=6;  // std::ops::RangeInclusive
..=7;   // std::ops::RangeToInclusive

Shell

Generate sequence

$ seq 5856 5859
5856
5857
5858
5859

Set delimiter by -s ('\n' As default)

$ seq -s ',' 5856 5859
5856,5857,5858,5859,

Ruby

>> ages = 18..30
=> 18..30
>> ages.entries
=> [18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
>> ages.include?(25)
=> true
>> ages.include?(33)
=> false
  • ..: inclusive,
  • ...: exclusive
>> (1..5).to_a
=> [1, 2, 3, 4, 5]
>> (1...5).to_a
=> [1, 2, 3, 4]

use === to test if a value is included in the range

>> (1..5) === 5
=> true
>> (1...5) === 5
=> false

Or use Range.new

>> Range.new(1,5).to_a
=> [1, 2, 3, 4, 5]
>> Range.new(1,5,true).to_a
=> [1, 2, 3, 4]