Python Tutorial / Create Lists and Add, Change and Remove Items

A list stores ordered items and allows changes. Distinguish operations that mutate the original list from functions that return a new list, especially when sorting or copying values.

Choose the operation by its purpose

Create a list with square brackets and access its first item at index zero. Lists can contain duplicates and different types, but values used in a total should have a consistent meaning and unit.

Operation Code Important behavior
Append one item items.append(value) A list argument becomes one nested item
Append several items items.extend(values) Adds each item from an iterable
Remove by position items.pop(index) Returns the removed item
Remove by value items.remove(value) Removes the first match; fails if absent

For the relevant APIs and platform requirements, see Python: datastructures.

List sharing and transformation build on the rules demonstrated in Build List, Dictionary and Set Comprehensions.

Run list changes and sorting

Save the complete code below as lists.py in a separate practice folder, using UTF-8. Run python lists.py in a terminal with your project virtual environment selected. Outside a virtual environment on macOS or Ubuntu, use python3 when that is your interpreter command.

amounts = [3500, 8000, 2500]
amounts.append(1000)
amounts[0] = 4000
removed = amounts.pop()
print(amounts, removed)
print(sorted(amounts))
print(amounts)
amounts.sort()
print(amounts)

Expected output:

[4000, 8000, 2500] 1000
[2500, 4000, 8000]
[4000, 8000, 2500]
[2500, 4000, 8000]

Separate mutation, sorting and copying

sorted(amounts) returns a new list and preserves the original order. amounts.sort() changes the existing list and returns None. Writing amounts = amounts.sort() therefore loses the list reference by assigning None.

A slice such as amounts[:] creates a shallow copy of the outer list. Nested mutable objects remain shared. A simple assignment other = amounts does not even copy the outer list; it creates another name for the same object. The object and copy lesson explores these effects.

list.sort() sorts the original list and returns None; sorted(iterable) returns a new list. Consequently, items = items.sort() assigns None rather than a sorted list. Neither operation makes a deep copy of nested objects.

Operation Result Observation
items.sort() None Changes original
sorted(items) New list Original order retained

Handle empty data and changes during iteration

Reading index zero or calling pop() on an empty list raises IndexError. Decide whether an empty input is valid or violates a requirement. remove() raises ValueError for an absent value.

Removing items from the list you are currently iterating can skip items as positions shift. Iterate over a copy or construct a new filtered list instead. Add zero to the original amounts, inspect both order and total, then restore the data. A change that preserves a sum can still change the structure.