Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Python

Idiom #254 Replace value in list

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

x = ["bar" if v=="foo" else v for v in x]

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

Explicit loop is the most readable
(replace {"foo" "bar"} x)

New implementation...