# Add a number to every item in list

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. Feb 11 '20 at 10:24
• 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))

• 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. Feb 11 '20 at 10:34
• 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. Feb 11 '20 at 10:38