How to Replace Items in a Python List

To replace items in a Python list, assign to an index: cities[1] = "Dallas". To replace by value, find the position with index() first, and replace every match with a list comprehension:

cities[1] = "Dallas"
statuses = ["processing" if s == "pending" else s for s in statuses]

US city lists, a shopping cart and order statuses keep the examples concrete; each was run on Python 3.12.5.

You’ll see replacement by index and slice, by value (and its ValueError), every match, conditional updates, mapping codes to names, and the in-place vs copy question.

Replace an item in a list by index

Lists are mutable, so you can assign straight to a position. Negative indexes count from the end, and a slice can replace several items, even a different number of them:

cities = ["Austin", "Denver", "Seattle", "Boston"]

cities[1] = "Dallas"          # by position
cities[-1] = "Miami"          # last item
print(cities)

cities[1:3] = ["Reno"]        # a slice can replace 2 items with 1
print(cities)

cities[1:1] = ["Tulsa", "Omaha"]   # empty slice = insert
print(cities)

Output:

['Austin', 'Dallas', 'Seattle', 'Miami']
['Austin', 'Reno', 'Miami']
['Austin', 'Tulsa', 'Omaha', 'Reno', 'Miami']
Command Prompt output of Python replacing list items by index, by negative index, by a slice and inserting with an empty slice
Denver becomes Dallas and Boston becomes Miami; the slice swaps two cities for Reno, and an empty slice inserts Tulsa and Omaha.

Slices grow or shrink the list; plain index assignment never does. To remove items rather than replace them, see removing the last element from a list.

Replace a list item by value

list.index(x) returns the position of the first match, and raises ValueError when there isn’t one:

cart = ["Mug", "Filters", "Beans", "Filters"]

i = cart.index("Filters")         # first match only
cart[i] = "Paper filters"
print(cart)

try:
    cart[cart.index("Kettle")] = "Electric kettle"
except ValueError as err:
    print("ValueError:", err)

if "Kettle" in cart:              # check first, or catch the error
    cart[cart.index("Kettle")] = "Electric kettle"
print(cart)

Output:

['Mug', 'Paper filters', 'Beans', 'Filters']
ValueError: 'Kettle' is not in list
['Mug', 'Paper filters', 'Beans', 'Filters']
Command Prompt output of Python replacing the first matching list item by value with index and a ValueError for a missing value
Only the first Filters becomes Paper filters; looking up Kettle raises ValueError until the code checks with in first.

Note that only the first “Filters” changed. To find every repeated value, see finding duplicates in a Python list.

How do I replace all occurrences in a list?

A comprehension builds a new list with every match replaced. If the list must change in place, loop with enumerate(). Conditions work the same way:

statuses = ["pending", "shipped", "pending", "delivered", "pending"]

new_list = ["processing" if s == "pending" else s for s in statuses]
print(new_list)

for i, s in enumerate(statuses):          # in place
    if s == "pending":
        statuses[i] = "processing"
print(statuses)

prices = [19.99, 129.00, 54.50, 249.99]
sale = [round(p * 0.9, 2) if p > 100 else p for p in prices]
print(sale)

Output:

['processing', 'shipped', 'processing', 'delivered', 'processing']
['processing', 'shipped', 'processing', 'delivered', 'processing']
[19.99, 116.1, 54.5, 224.99]
Command Prompt output of Python replacing every pending status with a list comprehension and an enumerate loop, plus a 10% discount over $100
All three pending statuses become processing both ways, and only the prices above $100 get 10% off.

I round money after the calculation, never before. For more on that, see rounding numbers to 2 decimal places.

Replace list items with a dictionary mapping

When many values map to new ones, a dict lookup beats a chain of if statements. dict.get(x, x) leaves unknown values unchanged. For text inside each string, call str.replace() per item:

codes = ["TX", "CA", "NY", "TX", "WA"]
names = {"TX": "Texas", "CA": "California", "NY": "New York"}

print([names.get(c, c) for c in codes])          # unknown codes stay as they are

skus = ["mug-red-12oz", "mug-blue-12oz", "tumbler-red-20oz"]
print([s.replace("red", "crimson") for s in skus])

Output:

['Texas', 'California', 'New York', 'Texas', 'WA']
['mug-crimson-12oz', 'mug-blue-12oz', 'tumbler-crimson-20oz']

WA stays WA because it isn’t in the mapping, which is why I default to get(x, x). For replacing several different characters inside one string, see replacing multiple characters in a string.

Replace items in place or in a copy?

Two names can point to the same list, so an in-place change shows up through both. Slice assignment, items[:] = ..., edits the list a caller passed in:

original = ["Austin", "Denver", "Seattle"]
same = original                         # another name for the SAME list
copy = original[:]                      # a separate list

original[0] = "Dallas"
print("original:", original)
print("same:    ", same)
print("copy:    ", copy)

def shout(items):
    items[:] = [x.upper() for x in items]   # slice assignment edits the caller's list

shout(copy)
print("copy after shout():", copy)

Output:

original: ['Dallas', 'Denver', 'Seattle']
same:     ['Dallas', 'Denver', 'Seattle']
copy:     ['Austin', 'Denver', 'Seattle']
copy after shout(): ['AUSTIN', 'DENVER', 'SEATTLE']
Command Prompt output of Python showing an in-place list change visible through an alias but not a copy, and slice assignment inside a function
Changing original also changes same but not copy, and shout() uppercases the copy through slice assignment.

Copy with items[:] or list(items) when the original must stay intact. Aliasing works the same way with dictionaries, as in copying a Python dictionary.

List replacement methods compared

GoalCodeChanges the original?
One positionlst[i] = xYes
Several positionslst[a:b] = [...]Yes
First matchlst[lst.index(old)] = newYes
All matches, new list[new if x == old else x for x in lst]No
All matches, in placefor i, x in enumerate(lst)Yes
Map codes to values[m.get(x, x) for x in lst]No

These list guides build on what you just did:

Frequently asked questions

How do I replace an item in a Python list?

Assign to its index: my_list[2] = "new value".

How do I replace a value when I don’t know its index?

Use my_list[my_list.index(old)] = new, after checking old in my_list.

How do I replace all occurrences of a value?

Use [new if x == old else x for x in my_list], or an enumerate loop to change it in place.

Why did my other variable change too?

Both names point to the same list. Copy it with my_list[:] first.

Can I replace two items with three?

Yes, with slice assignment: my_list[1:3] = [a, b, c] resizes the list.

Where are list operations documented?

See More on Lists in the Python tutorial.