Sling Academy
Home/Python/Python: Replacing/Updating Elements in a List (with Examples)

Python: Replacing/Updating Elements in a List (with Examples)

Last updated: June 06, 2023

This concise, example-based article gives you some solutions to replace or update elements in a list in Python.

Using indexing or slicing

If you want to update or replace a single element or a slice of a list by its index, you can use direct assignment with the [] operator. This is usually the simplest and fastest way to modify a list element or slice.

Example:

# create a list of numbers
my_list = [1, 2, 3, 4, 5]
print(my_list)
# [1, 2, 3, 4, 5]

# replace the second element with 10 using indexing
my_list[1] = 10
print(my_list)
# [1, 10, 3, 4, 5]

# replace the last two elements with 6 and 7 using slicing
my_list[-2:] = [6, 7]
print(my_list)
# [1, 10, 3, 6, 7]

This approach doesn’t create a new list but changes the original list.

Using list comprehension

If you want to update or replace multiple elements in a list based on a condition or a function, you can use list comprehension to create a new list with the updated or replaced elements. This is usually more concise and readable than other approaches. However, it may also create a new list object in memory, which may be less efficient than modifying the original list in place.

Code example:

# create a list
my_list = [1, 2, 3, 4, 5]

# create a new list with all even numbers doubled using list comprehension
new_my_list = [x * 2 if x % 2 == 0 else x for x in my_list]

print(f"The original list: {my_list}")
print(f"The new list: {new_my_list}")

Output:

The original list: [1, 2, 3, 4, 5]
The new list: [1, 4, 3, 8, 5]

With this approach, the original list is intact.

Using the enumerate() function

If you want to update or replace multiple elements in a list in place (without creating a new list) based on a condition or a function, you can use the enumerate() function to loop over the list and get both the index and the value of each element. Then, you can use direct assignment to modify the element in the original list. This may be more efficient than creating a new list object in memory. However, it may also be less concise and readable than using a list comprehension.

Example:

# create a list of letters
my_list = ["blue", "red", "green", "orange", "yellow", "purple"]

for index, value in enumerate(my_list):
    # if index is even or the length of the value is less than 5
    # replace the value with an asterisk
    if index % 2 == 0 or len(value) < 5:
        my_list[index] = "*"

print(my_list)

Output:

['*', '*', '*', 'orange', '*', 'purple']

Use a for loop or a while loop

You can also use a for loop or a while loop instead of the enumerate() function. However, the code will be a little bit longer.

Example (for loop):

# create a list of words
my_list = ["caramel", "chocolate", "vanilla", "strawberry", "mint"]

# capitalize the first letter of words whose length is greater than 7
for i in range(len(my_list)):
    if len(my_list[i]) > 7:
        my_list[i] = my_list[i].capitalize()
print(my_list)

Output:

['caramel', 'Chocolate', 'vanilla', 'Strawberry', 'mint'

Another example (white loop):

import pprint

employees = [
    {
        "name": "Wolf",
        "salary": 50000,
    },
    {
        "name": "Turtle",
        "salary": 60000,
    },
    {
        "name": "Demon of the Abyss",
        "salary": 65000,
    }
]

# using a while loop to update the salary of each employee (+20%)
i = 0
total_employees = len(employees)
while i < total_employees:
    employees[i]["salary"] = employees[i]["salary"] * 1.2
    i += 1

pprint.pprint(employees)

Output:

[{'name': 'Wolf', 'salary': 60000.0},
 {'name': 'Turtle', 'salary': 72000.0},
 {'name': 'Demon of the Abyss', 'salary': 78000.0}]

pprint is a standard module of Python. I used it in the example above just to make the output easier to read. You can use the print() function if you don’t care how your output looks.

Next Article: Ways to Combine Lists in Python

Previous Article: Python: How to Check If a List Is Empty (3 Approaches)

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots