Skip to content

Module 8 · Python Data Structures — topic 8 of 22

Updating elements

Change items in a list: assign by index, update with enumerate, transform every item with a comprehension, update nested lists and objects, and understand when in-place updates affect other names.

Beginner 10 min read·Lesson 111 of 306 in Python Programming

Learning objectives

  • Update items by index
  • Transform every item in place or into a new list
  • Update items inside nested lists

Definition

Change items in a list: assign by index, update with enumerate, transform every item with a comprehension, update nested lists and objects, and understand when in-place updates affect other names.

Introduction

Updating means changing the value of existing items without adding or removing any: correcting a typo, applying a discount to every price, or marking a task as done.

Why it matters

Data changes over time. Knowing how to update one item, several items or all items, and whether to change the list in place or create a new one, keeps data consistent and avoids accidental changes elsewhere.

Detailed explanation

Assign to an index: items[i] = new_value.

Updating with a for loop over the items doesn’t work: for p in prices: p = p * 2 only rebinds the loop variable. Loop over positions with enumerate and assign items[i].

A comprehension creates a new transformed list: [p * 0.9 for p in prices]. Assign it back to the same name if you want to replace the old list.

Slice assignment items[:] = [...] updates the existing list object in place, which other names sharing it will see.

Nested data: grid[r][c] = value updates one cell; for a list of dictionaries, records[i]["field"] = value updates one field.

Mutable items such as dictionaries inside a list can be updated through the loop variable, because the variable refers to the same object.

Syntax

Python
items[i] = value
for i, item in enumerate(items):
items[i] = transform(item)
items = [transform(x) for x in items]
  • Assign by index to change one item.
  • enumerate gives positions for in-place updates.
  • A comprehension builds a replacement list.

Code examples

Index assignment and the loop-variable trap

Python
prices = [100, 250, 80]
prices[1] = 240
for p in prices:
p = p * 2
print(prices)
Output
[100, 240, 80]

Rebinding p inside the loop doesn’t change the list.

Updating every item

Python
prices = [100, 240, 80]
for i, p in enumerate(prices):
prices[i] = round(p * 1.18, 2)
print(prices)
discounted = [p * 0.9 for p in prices]
print([round(d, 2) for d in discounted])
Output
[118.0, 283.2, 94.4]
[106.2, 254.88, 84.96]

More examples

Updating records in a list

Python
tasks = [
{"title": "Read chapter", "done": False},
{"title": "Solve exercises", "done": False},
{"title": "Revise notes", "done": False},
]
for task in tasks:
if task["title"].startswith("Read"):
task["done"] = True
tasks[2]["title"] = "Revise notes (30 min)"
for t in tasks:
mark = "x" if t["done"] else " "
print(f"[{mark}] {t['title']}")
shared = tasks
tasks[:] = [t for t in tasks if not t["done"]]
print(len(shared), "tasks left in the shared list")
Output
[x] Read chapter
[ ] Solve exercises
[ ] Revise notes (30 min)
2 tasks left in the shared list

Step-by-step explanation

  • The loop variable task refers to each dictionary, so changing task["done"] updates the item in the list.
  • tasks[2]["title"] updates one field of the third task.
  • The display loop shows [x] for done tasks.
  • tasks[:] = ... replaces the contents of the same list object, so shared sees the change too.

Expected output

Running “Updating records in a list” prints exactly:

TextOutput
[x] Read chapter
[ ] Solve exercises
[ ] Revise notes (30 min)
2 tasks left in the shared list

Practical applications

  • To-do apps mark tasks done by updating a field in a list of task records.
  • Price-update scripts apply a percentage change to every product.
  • Games update the board cell where a player moves.

Best practices

  • Use enumerate when updating in place.
  • Use comprehensions when a new list is acceptable.
  • Be aware whether other names share the list you update.

Common mistakes

Rebinding the loop variable

Avoid

for name in names:
name = name.title()

Prefer

names = [name.title() for name in names]

Assigning to the loop variable doesn’t change the list item.

Updating a copy by mistake

Avoid

row = grid[0][:]
row[0] = "X" # grid unchanged

Prefer

grid[0][0] = "X"

A slice is a new list; update the original by indexing it directly.

Key takeaways

  • items[i] = x updates one item.
  • Loop variables can’t update immutable items; use indexes or comprehensions.
  • Mutable items (like dicts) can be updated through the loop variable.

Try it yourself

  1. 1
    Capitalise every name in a list in place using enumerate.
  2. 2
    In a 3 × 3 grid, set every cell on the main diagonal to 1.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

13 questions cover the “Python Data Structures” module. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this module