modify list elements on a condition
<p>I am new to Python but have C/C++ background.
I am trying to modify a 2D list (list of lists) elements that satisfy a condition.
All I could come up with is the following solution:</p>

<pre><code>tsdata = [[random.random() for x in range(5)] for y in range(5)]
def check(tsdata):
    for i in range(len(tsdata)):
        for j in range(len(tsdata[i])):
            if (tsdata[i][j] &lt; min_value) or (tsdata[i][j]&gt; max_value):
                tsdata[i][j] = 0
check(tsdata)
</code></pre>

<p>I am sure there is a better solution which is actually suitable for Python but can't think of anything else that actually works. </p>

<p>EDIT: Actually, the list tsdata is a function argument and I am trying to modify it so some of your answers do not work. I have edited the code so this is clear.</p>

<p>Welcome to the world of simplicity and compact statements.</p>

<pre><code>tsdata_mod = [[0 if (x &lt; min_value or x &gt; max_value) else x for x in y] for y in tsdata]
</code></pre>

<p>or in function mode:</p>

<pre><code>def check(my_list):
    my_list_mod = [[0 if (x &lt; min_value or x &gt; max_value) else x for x in y] for y in tsdata]
    return my_list_mod

tsdata_mod = check(tsdata)
</code></pre>

<p>The above is in my opinion a very "pythonic" way to go about this task.</p>

<hr>

<p>Also when looping through containers such as lists for example you don't do:</p>

<pre><code>for i in range(len(tsdata)):
    for j in range(len(tsdata[i])):
        # do something with "tsdata[i]","tsdata[i][j]"
</code></pre>

<p>But rather:</p>

<pre><code>for sublist in tsdata:
    for entry in sublist:
        # do something with "sublist", "entry"
</code></pre>

<p>And if you really need the indexes (which in your case you don't) you use the <code>enumerate()</code> function like so:</p>

<pre><code>for i_sub, sublist in enumerate(tsdata):
    for i_entry, entry in enumerate(sublist):
        # do something with "i_sub", "sublist", "i_entry", "entry"
</code></pre>

python list