python
string-manipulation
list
find-and-replace
duplicate-question

Find and replace string values in list

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Finding and replacing strings in a Python list can mean different operations. Sometimes you want to replace whole list items that exactly match a target value. Other times you want to replace a substring inside every string element. The cleanest solution depends on which of those behaviors you actually need.

Replace Exact List Items

If you want to replace only elements that exactly equal a target string, a list comprehension is usually the clearest option.

python
1words = ["apple", "banana", "apple", "pear"]
2
3updated = ["orange" if item == "apple" else item for item in words]
4
5print(updated)

Output:

text
['orange', 'banana', 'orange', 'pear']

This creates a new list and leaves the original list unchanged, which is often a good default because it avoids accidental side effects.

Update the List In Place

If you really want to modify the existing list object, loop with indexes:

python
1words = ["apple", "banana", "apple", "pear"]
2
3for i, item in enumerate(words):
4    if item == "apple":
5        words[i] = "orange"
6
7print(words)

This is useful when other parts of your program already hold a reference to the same list and should see the updated values.

Replace Substrings Inside Each String

Sometimes the list items are not exact matches. Instead, you want to replace text inside each element. In that case, use the string method replace.

python
1items = ["error-001", "error-002", "warning-001"]
2
3updated = [item.replace("error", "issue") for item in items]
4
5print(updated)

Output:

text
['issue-001', 'issue-002', 'warning-001']

This is a different task from exact list-item replacement. The entire list element is not being matched as a single unit. Only part of each string is being transformed.

Replace Multiple Values with a Mapping

If several replacements are needed, a dictionary-based lookup can be cleaner than many nested if expressions.

python
1words = ["low", "medium", "high", "medium"]
2mapping = {
3    "low": "L",
4    "medium": "M",
5    "high": "H",
6}
7
8updated = [mapping.get(item, item) for item in words]
9print(updated)

This scales well when you have a fixed replacement table and want unmatched values to stay unchanged.

Handle Nested or Mixed Lists Carefully

The examples above assume a flat list of strings. If the list contains nested lists, None, numbers, or other object types, string methods such as replace will fail unless you validate the data first.

For example:

python
1values = ["apple", None, "banana"]
2
3updated = [
4    item.replace("a", "A") if isinstance(item, str) else item
5    for item in values
6]
7
8print(updated)

Type checks make the operation safer when the list contents are not guaranteed to be homogeneous.

Choosing the Right Pattern

A simple rule helps:

  • exact element match: conditional replacement
  • substring inside each string: str.replace
  • many exact replacements: dictionary lookup
  • existing list object must change: indexed in-place update

Once you define the intended behavior precisely, the code usually becomes short and readable.

Common Pitfalls

One common mistake is using str.replace when you actually wanted to replace only list elements that exactly equal a value. Substring replacement changes text inside matching elements, which may be broader than intended.

Another mistake is forgetting that a list comprehension builds a new list. If other code still holds the original list, it will not see those changes unless you reassign the variable or modify the list in place.

Developers also sometimes assume every list element is a string. Mixed data can raise exceptions when string methods are called on non-string values.

Finally, be careful with replacement rules that overlap. If one replacement changes text into something another rule also matches, the order of operations starts to matter.

Summary

  • Decide first whether you are replacing exact list elements or substrings inside each string.
  • Use a list comprehension for clean exact-value replacement into a new list.
  • Use indexed assignment when the original list object must be modified in place.
  • Use str.replace for substring transformations.
  • Validate mixed data before calling string methods on every element.

Course illustration
Course illustration

All Rights Reserved.