Search code examples
pythoncoding-style

Alter elements of a list


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?


Solution

  • bool_list[:] = [False] * len(bool_list)
    

    or

    bool_list[:] = [False for item in bool_list]