Categories
Python Answers

How to modify list entries during for loop with Python?

Spread the love

Sometimes, we want to modify list entries during for loop with Python.

In this article, we’ll look at how to modify list entries during for loop with Python.

How to modify list entries during for loop with Python?

To modify list entries during for loop with Python, we can use list comprehension.

For instance, we write

a = [1, 3, 5]
b = a
a[:] = [x + 2 for x in a]
print(b)

to write [x + 2 for x in a] to add 2 to each entry in a.

And then we assign the entries back to b since the slice assignment and avoids changing the entries in a

Conclusion

To modify list entries during for loop with Python, we can use list comprehension.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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