Lisp - Position of Sequence Element



In Lisp, we can find an element's position within Sequence (list or vector) using position function. An element position or index starts from 0. Following is the usage of position function.

(position item sequence)

Arguments

  • item− item to search.

  • sequence− sequence to be searched.

Returns

This function returns the position of the item found, nil otherwise.

Example - Position of an item in a list

main.lisp

; get and print the position of c; 2
(print (position 'c '(a b c d e f)))

; get and print the position of g; nil
(print (position 'g '(a b c d e f)))

Output

When you execute the code, it returns the following result −

C
NIL

Example - Position of an item in a vector

main.lisp

; get and print the position of c; 2
(print (position 'c #(a b c d e f)))

; get and print the position of g; nil
(print (position 'g #(a b c d e f)))

Output

When you execute the code, it returns the following result −

C
NIL

Key Parameters

position function accepts many optional parameters to customize our search.

  • :from-end if passed as t (true), search starts from the end of the sequence.

  • :start start index of the sequence for search.

  • :end end index of the sequence for search

  • :test a comparison function to compare elements of the sequence. Useful for custom equality checks.

  • :key a mapping function to be applied on each element of sequence before comparison. Useful, when we need to compare elements based on specific attributes of the elements.

Example - Searching from End

main.lisp

; get and print the position of last c in list; 4
(print (position 'c '(a b c d c f) :from-end t))

; get and print the position of last c in vector; 4
(print (position 'c #(a b c d c f) :from-end t))

Output

When you execute the code, it returns the following result −

4
4

Example - Searching within sublist

main.lisp

; get and print the position of c in sub part of list
(print (position 'c '(c b c d c f) :start 2 :end 4))

; get and print the position of c in sub part of vector
(print (position 'c #(c b c d c f) :start 2 :end 4))

Output

When you execute the code, it returns the following result −

2
2

Example - Searching using custom method

main.lisp

; get and print the position of (1 2) list using equal method
(print(position '(1 2) '((1 1) (1 2) (1 3)) :test #'equal))

Output

When you execute the code, it returns the following result −

1
Advertisements