Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 932
Dan Homerick Avatar asked Jan 03 '09 20:01

Dan Homerick


People also ask

Can you change elements in a list?

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.

How do you replace text in a list in Python?

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 .


1 Answers

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.

like image 88
Greg Hewgill Avatar answered Sep 28 '22 04:09

Greg Hewgill