# Replacing large numbers

Imagine I have the following list

l = {{1,2,3},{4,10^(16),5}}


How do I efficiently replace the large number by a number (zero, for example). I can't seem to do it for a list of lists. Any ideas?

• l /. _?(# > 1000 &) -> 0 ? Commented Jun 14, 2022 at 16:31

You could use 3-arg Clip:

Clip[l, {-Infinity, 10^10}, {0, 0}]


{{1, 2, 3}, {4, 0, 5}}

where I used 10^10 as the threshold.

Using Condition:

l /. x_Integer /; x > 10^6 -> 0
(*{{1, 2, 3}, {4, 0, 5}}*)


Or in the same way:

l /. x_?NumericQ /; x > 10^6 -> 0
(*{{1, 2, 3}, {4, 0, 5}}*)

l = {{1, 2, 3}, {4, 10^(16), 5}}


Define a high, low threshold as well as a substitute.

thlow = 2;
thhi = 3;
subst = 11;


Find positions of the entries that fall within the limits [2,3]:

pos = Position[l, x_ /; thlow <= x <= thhi, Infinity, Heads -> False]


{{1, 2}, {1, 3}}

To delete:

Delete[l, pos]


To replace with the substitute:

ReplacePart[l, Thread[pos -> subst]]


{{1, 11, 11}, {4, 10000000000000000, 5}}

I'm assuming you want something generalizable. Let's say your threshold is 10^10, then something like this:

Map[If[# > 10^10, 0, #] &, l, {2}]


You could also use ReplaceAll:

ReplaceAll[l, _?(GreaterThan[10^10]) -> 0]

list = {{1, 2, 3}, {4, 10^16, 5}};

big = 10^10;

p = Position[list, x_ /; x > big]


{{2, 2}}

Using ReplaceAt (new in 13.1)

ReplaceAt[_ :> 0, p] @ list


{{1, 2, 3}, {4, 0, 5}}

Using MapAt

MapAt[0 &, p] @ list


{{1, 2, 3}, {4, 0, 5}}