8

Suppose I have a nested list of the following:

list={{1,2},{5,8},{4,1}...}  

I would like to add a number to each first term of the list. The output would be like the following:

{{1+x,2},{5+x,8},{4+x},1}...}

Fermi
  • 121
  • 1

6 Answers6

18
list = {{1, 2}, {5, 8}, {4, 1}};

Apply, Function:

{#1 + x, #2} & @@@ list
(* {{1 + x, 2}, {5 + x, 8}, {4 + x, 1}} *)

Map:

# + {x, 0} & /@ list    
(* {{1 + x, 2}, {5 + x, 8}, {4 + x, 1}} *)

Part, Transpose:

Transpose[{list[[All, 1]] + x, list[[All, 2]]}]    
(* {{1 + x, 2}, {5 + x, 8}, {4 + x, 1}} *)

MapAt:

MapAt[x + # &, list, {All, 1}]
(* {{1 + x, 2}, {5 + x, 8}, {4 + x, 1}} *)

Transpose only:

Transpose[Transpose@list + {x, 0}]
(* {{1 + x, 2}, {5 + x, 8}, {4 + x, 1}} *)

Replace:

Replace[list, {a_, b_} :> {a + x, b}, {1}]
(* {{1 + x, 2}, {5 + x, 8}, {4 + x, 1}} *)

Inner:

Inner[Plus, list, {x, 0}, List]
(* {{1 + x, 2}, {5 + x, 8}, {4 + x, 1}} *)
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
3
list = {{1, 2}, {5, 8}, {4, 1}};

Using Threaded (new in 13.1)

list + Threaded[{x, 0}]

{{1 + x, 2}, {5 + x, 8}, {4 + x, 1}}

eldo
  • 67,911
  • 5
  • 60
  • 168
3

Using SubsetMap:

list = {{1, 2}, {5, 8}, {4, 1}};

SubsetMap[# + x &, list, {All, 1}]

{{1 + x, 2}, {5 + x, 8}, {4 + x, 1}}

Syed
  • 52,495
  • 4
  • 30
  • 85
3
list = {{1, 2}, {5, 8}, {4, 1}};

Using Cases:

Cases[list, {a_, b_} :> {a + x, b}]

({{1 + x, 2}, {5 + x, 8}, {4 + x, 1}})

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44
2

First and foremost, I have to say that the solution using Threaded looks like the nicest one to me. Kudos to @eldo.

I want to demonstrate the use of ThroughOperator that was developed by @Sjoerd Smit. To the extend of my knowledge it was first suggested in this answer.

In this example we do

ResourceFunction["ThroughOperator"][{#1 + x &, #2 &}] @@@ list

{{1 + x, 2}, {5 + x, 8}, {4 + x, 1}}

A not so normal way of doing it is to use Outer

Transpose[{First /@ Join @@@ Outer[Plus, list, {x, 0}], 
  Last /@ Join @@@ Outer[Plus, list, {x, 0}]}]
bmf
  • 15,157
  • 2
  • 26
  • 63
2
list + ConstantArray[{x,0},Length@list]


(* {{1+x,2},{5+x,8},{4+x,1}} *)
user1066
  • 17,923
  • 3
  • 31
  • 49