Get list element by position
Asked Answered
L

2

9

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].

Louiselouisette answered 21/3, 2016 at 10:30 Comment(6)
Possible Duplicate: #4288792Maimonides
No it's not maybe I wasn't clear. I want to give a number and the return value will be the element of this position like return lab[0]Louiselouisette
In Common Lisp is it (nth index list), with index starting from 0.Tango
That's it, you can answer it if you want.Louiselouisette
Possible duplicate of Is there a better way to get the nth item in a list?Secund
Might be worth noting that all of these accessors take time proportional to n: writing code as if they didn't is one of the causes of the 'Lisp is slow' myth.Combat
T
23

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)
Tango answered 21/3, 2016 at 11:4 Comment(0)
L
5

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)
Laundress answered 21/3, 2016 at 11:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.