what is D's idiom of Python's list.extend(another_list)?
Ali Çehreli
acehreli at yahoo.com
Mon Jun 21 08:58:26 UTC 2021
On 6/20/21 10:36 PM, mw wrote:
> i.e append an array of elements into another array:
>
>
> ```Python
> x = [1, 2, 3]
> x.extend([4, 5])
> print(x) # [1, 2, 3, 4, 5]
> ```
>
> Thanks.
There is also std.range.chain, which can visit multiple ranges in
sequence without copying elements. This is a lifesaver when the arrays
are very large.
import std.range;
import std.algorithm;
void main() {
auto a = [ 1, 2, 3 ];
auto b = [ 4, 5 ];
auto expected = iota(1, 6);
assert(chain(a, b).equal(expected));
}
Ranges can be very useful e.g. to sort elements of different random
access ranges:
import std.range;
import std.algorithm;
void main() {
auto a = [ 5, 1, 3 ];
auto b = [ 4, 2 ];
auto expected = iota(1, 6);
// This time we sort:
assert(chain(a, b).sort.equal(expected));
// What? :)
assert(a == [ 1, 2, 3]);
assert(b == [ 4, 5 ]);
}
Ali
More information about the Digitalmars-d-learn
mailing list