# How do I replace elements in a list matching a pattern?

I have a list: {0, 1, 1, 1, 2, 2, 2, 6}. I want to replace all the elements that are greater than 1 with the integer 1. In other words, I want Mma to return the list {0,1,1,1,1,1,1,1,1}.

• Unitize[data] or Clip[data], maybe? Mar 31, 2020 at 15:57
• lst = Table[RandomInteger[10], 10] Map[Min[#, 5] &, lst] 5 as an example. You should use 1. Mar 31, 2020 at 16:13
• lst /. x_ /; x > 1 -> 1  Mar 31, 2020 at 19:12

I just googled "wolfram mathematica replace if". Based on the first link I was able to figure it out in a minute!

lst = {0, 1, 1, 1, 2, 2, 2, 6};
lst /. {x_?(# > 1 &) -> 1}
{0, 1, 1, 1, 1, 1, 1, 1}


Usual approach would be to use ReplaceAll:

list = {0, 1, 1, 1, 2, 2, 2, 6};
list/.{x_?(# > 1 &) -> 1}


A slick approach would be

Boole /@ GreaterEqualThan[1] /@ list


Or even

Map[Min[#, 1] &, list]


Faster approach would be to use:

Unitize[list]
Clip[list]


All of them would give you:

{0, 1, 1, 1, 1, 1, 1, 1}


I just ran list = Table[RandomInteger[10], 100000] and used Mr.Wizard's timeAvg function:

list /. {x_?(# > 1 &) -> 1} // timeAvg
Boole /@ GreaterEqualThan[1] /@ list // timeAvg
Map[Min[#, 1] &, l] // timeAvg
Unitize[l] // timeAvg
Clip[l] // timeAvg


0.0690836

0.0559747

0.00204779

0.000139352

0.00022492

• Thank you, this is very helpful. Mar 31, 2020 at 17:03