bhylu.com

Advertisements

Change List Items

Change a list item when the sequence itself is meant to be mutable. Assignment to an index replaces the object at that position.

Understand the idea

Slice assignment can replace several positions at once and may change the length. Other names referring to the same list observe the change. If callers need an unchanged original, make the copying policy explicit rather than mutating data unexpectedly.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

stock = [8, 4, 0]
stock[1] = 6
stock[2:] = [3, 5]
print(stock)

Read the result

The list becomes [8, 6, 3, 5]. The slice replacement grows the sequence.

Try one change

Replace the first two values with one combined value and predict the new length.