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