Python’s built-in functions are useful for manipulating lists.
Python makes it easy to modify, update, and replace elements in any list. This can be extremely helpful when you need to make changes to your data at scale. The methods available to manipulate lists i …
Python makes it easy to modify, update, and replace elements in any list. This can be extremely helpful when you need to make changes to your data at scale. The methods available to manipulate lists include append(), extend(), insert(), remove(), and pop().
# create a list
fruits = ["apple", "banana", "cherry"]
print(f"Original List: {fruits}") # Original List: ['apple', 'banana', 'cherry']
# use the index to replace an item
fruits[1] = "mango"
print(f"Modified List: {fruits}") # Modified List: ['apple', 'mango', 'cherry']
The list has been modified. The element at index 1 (“banana”) was replaced with “mango”.
Although lists are mutable in Python, sometimes you may need to replace an item from a list without modifying the original list (for example when working with large datasets). In that case, you can use the list() function to create a copy of the list. Here’s how it is done:
original_fruits = ["apple", "banana", "cherry"]
modified_fruits = original_fruits[:] # creates a copy of the list
print(f"Original List: {original_fruits}") # Original List: ['apple', 'banana', 'cherry']
# replace an item in the copied list
modified_fruits[1] = "mango"
print(f"Modified List: {modified_fruits}") # Modified List: ['apple', 'mango', 'cherry']
The original list remains unchanged and only modified_fruits has been changed.