I have a list of booleans where occasionally I reset them all to false. After first writing the reset as:
for b in bool_list:
b = False
I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value. So I rewrote as:
for i in xrange(len(bool_list)):
bool_list[i] = False
and everything works fine. But I found myself asking, "Is that really the most pythonic way to alter all elements of a list?" Are there other ways that manage to be either more efficient or clearer?
The easiest way to replace an item in a list is to use the Python indexing syntax. Indexing allows you to choose an element or range of elements in a list. With the assignment operator, you can change a value at a given position in a list.
Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .
If you only have one reference to the list, the following may be easier:
bool_list = [False] * len(bool_list)
This creates a new list populated with False
elements.
See my answer to Python dictionary clear for a similar example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With