Logo

Programming-Idioms

  • Rust
  • Lua
  • Python

Idiom #254 Replace value in list

Replace all exact occurrences of "foo" with "bar" in the string list x

for i, v in enumerate(x):
  if v == "foo":
    x[i] = "bar"

Explicit loop is the most readable
for i, v in enumerate(x):
    if v == 'foo': x[i] = 'bar'
x = ["bar" if v=="foo" else v for v in x]

List comprehension
for v in &mut x {
    if *v == "foo" {
        *v = "bar";
    }
}
(replace {"foo" "bar"} x)

New implementation...