Skip to content

Update list in for loop Python | Example code

  • by

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"



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]

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)

Windows 10

Python 3.10.1

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

Leave a Reply

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