How to replace elements in a list in Python?

In Python, you can use indexing to replace elements in a list. Here are some methods to replace elements in a list:

  1. Replace elements directly using indexing.
my_list = [1, 2, 3, 4, 5]
my_list[0] = 10
print(my_list)  # 输出:[10, 2, 3, 4, 5]
  1. Use slicing to replace multiple elements.
my_list = [1, 2, 3, 4, 5]
my_list[1:4] = [10, 11, 12]
print(my_list)  # 输出:[1, 10, 11, 12, 5]
  1. put()
my_list = [1, 2, 3, 4, 5]
my_list.insert(2, 10)
print(my_list)  # 输出:[1, 2, 10, 3, 4, 5]
  1. using a list comprehension
my_list = [1, 2, 3, 4, 5]
new_list = [10 if x == 2 else x for x in my_list]
print(new_list)  # 输出:[1, 10, 3, 4, 5]

You can choose the appropriate method based on your specific needs to replace elements in the list.

bannerAds