VMware ESXi and vSphere Cluster Management
How to Modify Python Lists
Learn how to modify Python lists with index assignment, concatenation, append(), del, and slice assignment, including common errors and method selection.
Python lists are ordered collections that can hold multiple values. A list is mutable, which means its contents can be changed after the list is created.
For example, this list starts with three numbers:
values = [10, 20, 30]
Each item has a zero-based index, which is the numeric position used to access it. The first item is at index 0, the second is at index 1, and the third is at index 2.
| Index | Value |
|---|---|
0 | 10 |
1 | 20 |
2 | 30 |
Modifying a list changes the existing list object. This differs from evaluating an expression that creates a separate list. For example, values + [40] produces a new list; it does not change values unless you assign the result back to values.
Replace an Element by Index
Index assignment replaces one list element by assigning a new value to list[index]. Index 0 refers to the first element.
numbers = [10, 20, 30]
numbers[0] = 99
print(numbers[0])
print(numbers)
Output:
99
[99, 20, 30]
The assignment changes the first item from 10 to 99. The other items remain in their original positions.
The index must refer to an existing position. Assigning to an invalid index raises IndexError:
numbers = [10, 20, 30]
numbers[3] = 40 # IndexError
This list has indexes 0 through 2; index 3 does not exist. You can use len(numbers) to check the number of items, but the largest valid positive index is one less than that length.
Add Items with List Concatenation
Concatenation means combining lists with the + operator. The result is a new list.
base = [1, 2, 3]
additional = [4, 5]
combined = base + additional
print(base)
print(combined)
Output:
[1, 2, 3]
[1, 2, 3, 4, 5]
base remains unchanged because concatenation created a separate list and stored it in combined. If you want the combined result under the original variable name, assign it back:
base = base + additional
print(base) # [1, 2, 3, 4, 5]
Both operands of + must be lists. This causes an error:
values = [1, 2]
values + 3 # TypeError
To concatenate one value, put that value inside a list, such as values + [3].
Add One Item with append()
append() is a list method that adds one object to the end of the existing list. Because it changes the list in place, no assignment back to the variable is needed.
numbers = [10, 20, 30]
numbers.append(40)
print(numbers)
Output:
[10, 20, 30, 40]
append() accepts exactly one object argument. That object can be a number, string, or another kind of value.
If the one object is itself a list, the entire list becomes one nested item:
values = [1, 2]
values.append([3, 4])
print(values)
print(values[2])
Output:
[1, 2, [3, 4]]
[3, 4]
The result has three top-level items. The last item is a nested list, meaning a list stored as one item inside another list. It does not produce [1, 2, 3, 4].
Remove One Item with del
The del statement removes an item when its index is known:
letters = ["a", "b", "c", "d"]
del letters[1]
print(letters)
Output:
["a", "c", "d"]
The item at index 1, "b", was deleted. Items after the deleted position shift left: "c" moves from index 2 to index 1, and "d" moves from index 3 to index 2.
Deleting an index that does not exist raises IndexError:
letters = ["a", "b"]
del letters[2] # IndexError
Remove Several Items with Slice Assignment
A slice selects a range of list positions. Its usual form is list[start:stop]. The start index is included, but the stop index is excluded.
| Expression | Positions affected | Key rule |
|---|---|---|
list[0] | One item at index 0 | Index 0 is the first position |
list[1] | One item at index 1 | Index 1 is the second position |
list[:3] | Indexes 0, 1, and 2 | The stop index 3 is excluded |
list[start:stop] | Indexes from start through stop - 1 | Start is included; stop is excluded |
Slice assignment replaces the items selected by a slice. Assigning an empty list removes those selected items:
numbers = [0, 1, 2, 3, 4]
numbers[:3] = []
print(numbers)
Output:
[3, 4]
The slice numbers[:3] selects indexes 0, 1, and 2. Because index 3 is excluded, the items 3 and 4 remain.
You can remove another contiguous range by specifying both boundaries:
values = ["a", "b", "c", "d", "e"]
values[1:4] = []
print(values) # ["a", "e"]
Indexes 1, 2, and 3 are removed. Index 4 is outside the slice and remains.
Choosing the Appropriate Modification Method
| Task | Syntax pattern | Changes original list? | Result |
|---|---|---|---|
| Replace one indexed element | values[index] = replacement | Yes, in place | The selected item is replaced |
Combine two lists with + | combined = values + additional_values | No, unless assigned back | A new combined list |
Add one item with append() | values.append(item) | Yes, in place | One item is added at the end |
Delete one indexed element with del | del values[index] | Yes, in place | One item is removed |
| Delete a range using empty slice assignment | values[start:stop] = [] | Yes, in place | A contiguous range is removed |
- Use index assignment when replacing an existing item at a known position.
- Use
+when you need a combined result that is a distinct list. - Use
append()when adding one final item to an existing list. - Use
delwhen deleting one item at a known index. - Use empty slice assignment when deleting a contiguous range of items.
Troubleshooting Common Problems
The wrong item was changed or deleted
The usual cause is treating the first position as index 1. Python indexes start at 0. Print the indexes and values mentally or inspect them before changing the list:
values = ["red", "green", "blue"]
print(values[0]) # red
print(values[1]) # green
print(values[2]) # blue
append() added one nested item instead of multiple items
append() takes one object. When that object is a list, it adds the list as one nested item:
values = [1]
values.append([2, 3])
print(values) # [1, [2, 3]]
To add separate values while staying within these methods, call append() once for each value:
values = [1]
values.append(2)
values.append(3)
print(values) # [1, 2, 3]
Python also provides extend() for adding multiple items from an iterable; it is a related topic rather than the same operation as append().
The original list did not change after using +
Concatenation returns a new list. Store that result:
values = [1, 2]
additional = [3, 4]
combined = values + additional
print(values) # [1, 2]
print(combined) # [1, 2, 3, 4]
If changing the original variable is intended, assign the result back with values = values + additional.
An IndexError occurred
Check the current list length and use an index from 0 through len(values) - 1. A list can also become shorter after a deletion, so an index that was valid earlier may no longer exist.
A slice removed too many or too few items
Remember that the stop index is excluded. For example, values[:3] selects indexes 0, 1, and 2, not index 3.
Summary
- Lists are mutable, so their contents can change after creation.
- Indexes are zero-based: index
0is the first item. values[index] = replacementreplaces one item.values + other_valuescreates a new list, whileappend()changes the existing list in place.append(item)adds one object, including a list as one nested object.del values[index]removes one indexed item and shifts later items left.values[start:stop] = []removes a contiguous range, with the stop index excluded.- Invalid indexes for assignment or deletion raise
IndexError.