How do I add a number, say 2, to every item in a list?

(setq x '(1 2))

(+ 2 x)

(mapcar '2+ x)

(loop for i in x
      do (+ 2 i))

(dolist (i x)
  (+ 2 i))

None of the above work.

  • (+ 2 x) doesn't work because + takes numbers as arguments and returns their sum, and (mapcar '2+ x) doesn't work because there is no built-in function called 2+ (though you could define it yourself). The two loops work, but you are not saving the results of their computation anywhere, so the results are lost.
    – Basil
    Feb 11 '20 at 10:24
  • 1
    This Q and emacs.stackexchange.com/q/55440/105 are essentially the same question. One of them should be deleted. (@Basil: would you like to consolidate the underlying question as a community question?)
    – Drew
    Feb 11 '20 at 16:26

Possible solutions:

(mapcar (lambda (entry) (+ entry 2)) x)
(mapcar (apply-partially #'+ 2) x)

And if you need to update x, then setq it to the result of one of the above forms, e.g.:

(setq x (mapcar (apply-partially #'+ 2) x))

That's not very elegant (there's probably a much simpler answer) but this should work:

(setq x '(1 2 3 4))

(defun add-one (x)
  "Add 1 to each element of list X"
  (setq counter 0)
  (setq res x)
  (while (< counter (length x))
    (setcar (nthcdr counter res) (1+ (car (nthcdr counter x))))
    (setq counter (1+ counter)))

(add-one x)
  • 1
    Never destructively modify (e.g. using setcar) a quoted constant list, such as '(1 2 3 4), otherwise the constant will be modified globally and the same code may behave differently in each run. Instead, either initialise x to a new list, such as (list 1 2 3 4), before modifying it, or accumulate changes in a new list and set that as the value of x, thus replacing its old value.
    – Basil
    Feb 11 '20 at 10:34
  • 1
    Your looping logic is unidiomatic Elisp and inefficient, as it traverses the same list from the start for each element access. Idiomatic Elisp uses dolist, mapc, mapcar, or successive calls to cdr to go from one list element to another, without the need for indices or traversing the entire length each time. Lists are not random-access like arrays.
    – Basil
    Feb 11 '20 at 10:38
  • Thanks for the input! (Noobs make noob mistakes ;))
    – Philopolis
    Feb 11 '20 at 11:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.