1

Q: how do I pop an arbitrary element from a list?

Given the list '(a b c d e), pop returns a and destructively modifies the list to '(b c d e). How can I generalize this function so I could pop an arbitrary element (say, c)?

I'm almost sure I've seen this in a library somewhere, but can't remember where.

Drew
  • 75,699
  • 9
  • 109
  • 225
Dan
  • 32,584
  • 6
  • 98
  • 168
  • An afterthought: maybe you were just thinking of `delq`? Do you want to delete by position or value (in the latter case you probably don't need the value returned). – ebpa Oct 19 '17 at 14:53

1 Answers1

5

Simply (pop (nthcdr n my-list)):

(let ((x '(a b c d e)))
  (list (pop (nthcdr 2 x))
        x))
;; => (c (a b d e))
ebpa
  • 7,319
  • 26
  • 53
  • 2
    I think it's funny that I wrote a little function to `setcar` and `setcdr` of the `nthcdr` and was thinking of an appropriate name for the function and once I thought "pop-nthcdr" realized "oh! you could just write that!" – ebpa Oct 19 '17 at 14:38