Update list in for loop Python | Example code

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)

Output:

Update list in for loop Python

Another Example

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 and suggestions on this Python list topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.