Manuel Pap
Manuel Pap

Reputation: 1399

Get list element by position

I want to give a number and return the element of this position. List lab = (R K K K K) and I want to know if something like this (position 1 lab) exists on lisp. Like in C return lab[1].

Upvotes: 10

Views: 17402

Answers (2)

coredump
coredump

Reputation: 38967

For an operator that works on vectors and proper lists, see elt.

(let ((list (list 'a 'b 'c 'd)))
       (prog1 list
         (setf (elt list 1) 1)))
=> (A 1 C D)

Upvotes: 5

Renzo
Renzo

Reputation: 27454

In Common Lisp the operator that gets the n-th element of a list is called nth (see the manual):

(nth 2 '(a b c d))  ; returns C

A related operator is nthcdr that returns the rest of the list starting from the n-th element:

(nthcdr 2 '(a b c d)) ; returns (C D)

Upvotes: 24

Related Questions