Skip to content
On this page

Lists โ€‹

The type of lists over type t is sp.TList(t).
All elements need to be of the same type t.
The corresponding type in Michelson is

Michelson list.

See reference Lists template.

Literals โ€‹

sp.list(lย = ...,ย tย = ...)
Define a list of (optional) elements in l whose optional type is t.

Standard Python lists are also accepted. [3,ย 2,ย 1], ["aa",ย "bb",ย "cc"].

Example โ€‹

python
aNatList    = sp.list([3, 2, 1], t = sp.TNat)
aStringList = sp.list(["aa", "bb", "cc"], t = sp.TString)
# Uses type inference to determine the type
anotherList = [3, 2, 1];
Michelson NIL

Operations โ€‹

Push an element on top of a list โ€‹

<list>.push(<element>)
Push an element on top of list.

sp.cons(x, xs)
Create a new list with x on top of list xs without affecting xs.

Example โ€‹

python
self.data.my_list = [3, 2, 1]

self.data.my_list.push(4)
# self.data.my_list is now [4, 3, 2, 1]

self.data.my_list2 = sp.cons(12, self.data.my_list)
# self.data.my_list2 is now [12, 4, 3, 2, 1]
# self.data.my_list is still [4, 3, 2, 1]
Michelson CONS

Obtaining Size โ€‹

sp.len(<list>)
Return the length of <list>.

Example โ€‹

python
size = sp.len([3, 2, 1])
Michelson SIZE

Concatenation โ€‹

sp.concat(myList)
Concatenate a list myList of sp.TString or sp.TBytes.

Example โ€‹

python
sp.concat(["Hello", " ", "World"]) # Hello World
Michelson CONCAT

Define a range โ€‹

sp.range(x, y,ย stepย = ...)
A list from x (inclusive) to y (exclusive) and step as incrementor. Useful in conjunction with sp.for loops.

Example โ€‹

python
sp.range(1, 5, step = 1) # [1, 2, 3, 4]

Reverse a list โ€‹

myList.rev()
Reverse a list.

Example โ€‹

python
myList       # [3, 2, 1]
myList.rev() # [1, 2, 3]

Match a list and expose its head and tail โ€‹

sp.match_cons(myList)
Match a list and expose its head and tail if any.

See reference Lists template.

python
with sp.match_cons(myList) as x1:
    self.data.head = x1.head
    self.data.tail = x1.tail
sp.else:
    self.data.head = "abc"

Please note that there is no way to perform random access on a list.

Iterate over a list โ€‹

sp.for x inย <list>:
To iterate on sp.TMap(key, value) or sp.TSet(elem), we first convert to an sp.TList(..) with <expr>.items(), <expr.keys(), expr.values() or expr.elements().

Example โ€‹

python
@sp.entrypoint
def sum(self, params):
    self.data.result = 0
    sp.for x in params:
        self.data.result += x