How to Update Python List Elements: Assignment by Index

Python lists are a “mutable” (changeable) data type. This means that even after creating a list, you can freely change the values of its contents (elements). This operation is essential when updating the status of data retrieved from a database or rewriting part of a settings list.

This article explains the basic method of updating (overwriting) specific elements in a list with new values.


目次

Updating Elements by Specifying an Index

The most basic way to update an element in a list is to specify the Index (position number) and set a new value using the assignment operator (=).

Syntax:

list_variable[index] = new_value

1. Updating with Positive Index (Starting from 0)

Python indexes start from 0. [0] refers to the first element, and [1] refers to the second. Let’s look at a list managing server statuses as an example.

# Server status list
server_statuses = ["Online", "Pending", "Offline", "Online"]
print(f"Before: {server_statuses}")

# Change the 2nd item (Index 1) "Pending" to "Maintenance"
server_statuses[1] = "Maintenance"

print(f"After:  {server_statuses}")

Output:

Before: ['Online', 'Pending', 'Offline', 'Online']
After:  ['Online', 'Maintenance', 'Offline', 'Online']

The value “Pending” at index 1 was overwritten with “Maintenance”.

2. Updating with Negative Index (Starting from -1)

You can also use negative indexes, such as [-1] (the last element) or [-2] (the second to last element), to update values just as you use them for reference.

server_statuses = ["Online", "Maintenance", "Offline", "Online"]
print(f"Before: {server_statuses}")

# Change the last item (Index -1) "Online" to "Error"
server_statuses[-1] = "Error"

print(f"After:  {server_statuses}")

Output:

Before: ['Online', 'Maintenance', 'Offline', 'Online']
After:  ['Online', 'Maintenance', 'Offline', 'Error']

Important Note: IndexError

This method is strictly for “replacing” existing values. If you try to assign a value to an index outside the range of the list (an index that does not exist), an IndexError will occur.

server_statuses = ["Online", "Maintenance", "Offline", "Error"]
# The list length is 4 (indices are 0, 1, 2, 3)

# Trying to assign to index 4 (which does not exist) causes an error
# server_statuses[4] = "New Server"
# IndexError: list assignment index out of range

If you want to add a new element to the end of the list, use the append() method (e.g., server_statuses.append("New Server")) instead of assignment.


Summary

  • You can easily update list elements using the syntax my_list[index] = new_value.
  • Both positive indexes (starting from 0) and negative indexes (starting from -1) can be used.
  • This operation replaces existing elements. Assigning to a non-existent index results in an IndexError.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次