Skip to content

Python for loop change value | Example code

  • by

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.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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading