An easy and simple way to update a list in for loop using a for-loop and list indexing in Python.
Example update list in for loop Python
Simple example code, use a for-loop with range(stop) as the iterator.
lst = ["a", "b", "c"] for i in range(len(lst)): lst[i] = lst[i] + "T" print(lst)
Use a list comprehension instead, with a slice assignment if you need to retain existing references to the list.
lst = [1, 3, 5] updated = lst lst[:] = [x + 2 for x in lst] print(updated)
Output: [3, 5, 7]
Do comment if you have any doubts or suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.