![]() |
VOOZH | about |
Lists in Python are mutable meaning their items can be changed after the list is created. Modifying elements in a list is a common task, whether we're replacing an item at a specific index, updating multiple items at once, or using conditions to modify certain elements. This article explores the different ways to change a list item with practical examples.
Using Indexing we update a specific item in the list by simply assigning a new value to the desired index.
Example:
[10, 25, 30, 40]
a[1] = 25 modifies the element at index 1 (second position) of the list, replacing 20 with 25.Let's explore some other methods to change list item
Table of Content
Slicing allows changing multiple items at once by specifying a range of indices. This method is useful for batch updates and has a time complexity of O(n) where n is the size of the slice.
Example:
[10, 21, 31, 40, 50]
Explanation:
a[1:3], we target the elements at indices 1 and 2 (i.e., 20 and 30). This slice specifies the range of items to be replaced.a[1:3] = [21, 31] replaces the selected slice with the new elements [21, 31].List comprehension is another simple way to update items in a list based on conditions. Here, we Iterate over the list and apply a condition or transformation and construct a new list with the updated values.
Example:
[20, 15, 40, 25]
[x * 2 if x % 2 == 0 else x for x in a], we iterate over each element in the list. For each element:x % 2 == 0), we double it (x * 2).If we want to modify elements in place a for loop with enumerate() allows us to iterate through the list while keeping track of indices.
Example:
[10, 20, 20, 30]
for loop with enumerate, we iterate through each index and value in the list. For each element: If the element is odd (x % 2 != 0), we add 5 to its value (a[i] += 5).a becomes [10, 20, 20, 30].map()The map() function can be used for functional-style updates by applying a function to each element. We use map() to apply the function and convert the result back to a list.
Example:
[11, 21, 31]
Explanation:
map function is combined with a lambda function to increment each element in the list by 1:lambda x: x + 1 defines an anonymous function that adds 1 to its input (x).map function applies this lambda to every element in the list a.