How to replace elements in a list using Python?

In Python, you can use indexes to replace elements in a list. Here are some example codes:

  1. Replace a single element with an index.
my_list = [1, 2, 3, 4, 5]
my_list[2] = 10
print(my_list)  # Output: [1, 2, 10, 4, 5]
  1. Replace multiple elements with slices.
my_list = [1, 2, 3, 4, 5]
my_list[1:3] = [10, 20]
print(my_list)  # Output: [1, 10, 20, 4, 5]
  1. Replace multiple elements using a loop.
my_list = [1, 2, 3, 4, 5]
for i in range(len(my_list)):
    if my_list[i] % 2 == 0:
        my_list[i] = my_list[i] * 2
print(my_list)  # Output: [1, 4, 3, 8, 5]

These are some common methods for replacing elements in a list, depending on your specific needs and logic.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds