Update list in-place, converting 'True'/'False' elements to 1/0
<p>In python, supposed I have a list: </p>

<pre><code>l = [ 'True', 'False', 'myname', 1, 0, 'foo' ] 
</code></pre>

<p>and I want to convert the <em>strings</em> <code>'True'</code> or <code>'False'</code> to <code>1</code> or <code>0</code>, what is the best way to do this and still retain the index that the value had originally? i.e. the output would look like: </p>

<pre><code>l = [  1, 0, 'myname', 1, 0, 'foo' ]
</code></pre>

<p>Thought I would offer a more robust solution if your list's items are <code>on</code>, <code>off</code>, <code>yes</code>, <code>no</code> etc (<em>refer to <a href="https://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool" rel="nofollow">documentation</a></em>).</p>

<pre><code>from distutils.util import strtobool
def convert_str_to_bool(l):
    result = []
    for item in l:
        try:
            result.append(strtobool(item))
        except:
            result.append(item)
    return result
</code></pre>

<p><strong>Sample Output:</strong></p>

<pre><code>&gt;&gt;&gt; l = [ 'True', 'False', 'myname', 1, 0, 'foo' ] 
&gt;&gt;&gt; print convert_str_to_bool(l)
[1, 0, 'myname', 1, 0, 'foo']
</code></pre>

python list dictionary