THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
Sometimes, We need to generate a fixed list with a sequence of numbers from 0 to N. This article, Shows multiple ways to create a list of 0 to n numbers.
There are multiple ways we can create a sequence of numbers in a list
generate()
function in a list creates a list with values generated with a given function.
Syntax:
List generate(length, Function,{growable})
The list is created with a length
attribute.
Function
is a generator function logic to have the values in a list
growable: false means the List is fixed in size.
Here is an example to create a list of sequence numbers from 0 to N.
void main() {
var sequenceNumbers = new List<int>.generate(20, (k) => k + 1);
print(sequenceNumbers);
}
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
collection for
in dart is used to create a list with manipulation of indexed values.void main() {
var numberList = [for (var i = 1; i <= 20; i++) i];
print(numberList);
}
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
To summarize, It is easy to create a sequence of numbers in a list with
list generate function
and collection for
with examples
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts