Skip to main content
2 of 2
added 5 characters in body
Drew
  • 79.1k
  • 10
  • 123
  • 257

Here is a non destructive version.

(defun replace-element-in-list (elem-src elem-dst ls &optional times comparison-fn)
  (setq times (or times (length ls)))
  (mapcar
   (lambda (item)
     (cond
      ((and (> times 0)
            (funcall (or comparison-fn #'eq) item elem-src))
       (cl-decf times)
       elem-dst)
      (t
       item)))
   ls))

(replace-element-in-list 2 "2" '(1 2 3 2 4))
;; => (1 "2" 3 "2" 4)

(replace-element-in-list 2 "2" '(1 2 3 2 4) 1)
;; => (1 "2" 3 2 4)

(replace-element-in-list "2" 2 '("1" "2" "3" "2" "4") nil #'string=)
;; => ("1" 2 "3" 2 "4")
xuchunyang
  • 14.8k
  • 1
  • 21
  • 42