Nim Iterators and Sequences — Lazy and Eager Collection Processing
DodaTech
Updated 2026-06-29
1 min read
In this tutorial, you will learn about Nim Iterators and Sequences. We cover key concepts, practical examples, and best practices to help you master this topic.
Nim provides iterators for lazy processing and sequences for dynamic arrays. Understanding both is key to writing efficient Nim code.
Iterators
# Custom iterator
iterator countdown(n: int): int =
var i = n
while i >= 0:
yield i
dec i
for i in countdown(5):
echo i # 5, 4, 3, 2, 1, 0
# Built-in iterators
for i in 0..5: echo i # Range
for i in items(@[1,2,3]): # Items in seq
for i in pairs(@[1,2,3]): # Index-value pairs
Sequences
var s = @[1, 2, 3] # Create
s.add(4) # Append
s.insert(0, 0) # Insert at index
s.delete(2) # Delete by index
# Map and filter
import sequtils
let doubled = s.mapIt(it * 2)
let evens = s.filterIt(it mod 2 == 0)
let sum = s.foldl(a + b)
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro