The subscript operator []
is used to extract elements from a list or characters from a string.
The index of the first element is 0
. Indexes may be negative to count from the end of the list or string; the index of the last element is -1
.
Yewslip>
list = ["first", "second", "last"]Yewslip>
print list[0], list[1], list[3], list[-1]first second (nil) last
Yewslip>
print "string"[1]t
A list of indexes may be used to extract several elements.
Yewslip>
print list[[-1, 0]][last, first]
A range of elements may also be selected by using an index in the form
or first
:last
. If first
:last
:step
first
is omitted, it defaults to 0
. If last
is omitted, it defaults to inf
. The element indexed by last
is excluded.
Yewslip>
print list[:2], list[2:], "string"[5:1:-1][first, second] [last] gnir
The subscript operator can also be used in assignment. In this case, the index of the element after the last may also be used to append values to the list.
Yewslip>
list[0] = "1st"Yewslip>
list[3] = "one more"Yewslip>
list[[1, 2]] = ["2nd", [3, 4, 5]]Yewslip>
print list[1st, 2nd, [3, 4, 5], one more]
Several indexes may be given to select items from lists within a list. This is equivalent to using []
several times.
Yewslip>
print list[2, 1]4
A scalar value is interpreted by the subscript operator as a list consisting of one value.
Yewslip>
print 42[0], 42[5]42 (nil)
String values are handled in a fashion similar to lists. The index refers to a character in the string. The result of the operator is a string of selected characters.
Yewslip>
print "string"[2]r
Yewslip>
print "string"[[0, -1]], "string"[:4]sg stri