Python for loop change value | Example code

Python for loop change value of the currently iterated element in the list example code.

foo = [4, 5, 6]

for idx, a in enumerate(foo):
    foo[idx] = a + 42
    print(foo)

Output:

Python for loop change value

Or you can use list comprehensions (or map), unless you really want to mutate in place (just don’t insert or remove items from the iterated-on list).

The same loop is written as a list comprehension looks like:

foo = [4, 5, 6]

foo = [a + 42 for a in foo]
print(foo)

Output: [46, 47, 48]

Change value of the currently iterated element in the list example

Use a for-loop and list indexing to modify the elements of a list.

a_list = ["a", "b", "c"]

for i in range(len(a_list)):
    a_list[i] = a_list[i] + a_list[i]

print(a_list)

Output: [‘aa’, ‘bb’, ‘cc’]

Do comment if you have any doubts and suggestions on this Python for loop code.

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.