How to use a list in Nim

Want to create a list (a resizable array of items) in Nim? You can do this with a sequence.

Creating a sequence

A sequence can be created, and added to:

var fruits = newSeq[string]()

echo fruits

or can be initialized with elements:

var fruits = @["apple", "banana"]
echo fruits

The output of the above samples is the same:

@["apple", "banana"]

Iterating over a sequence

To iterate over the list:

var fruits = @["apple", "banana"]
for fruit in fruits:
  echo fruit

Running this yields:


Testing existence of a value in the sequence

To test if the value exists in the list:

var fruits = @["apple", "banana"]
let appleExists = "apple" in fruits
echo appleExists

The contains method can also be used:

var fruits = @["apple", "banana"]
let appleExists = fruits.contains("apple")
echo appleExists

Running either of the above samples yields:


Deleting an entry from the list

An item can be deleted from the sequence:

var fruits = @["apple", "banana", "cherry"]
echo fruits

Running this yields:

@["apple", "cherry"]


Leave a comment

What color are brown eyes? (spam prevention)
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.