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>Your solution is not bad, but the following could be more simpler to understand. (depends of how your code should evolve later)</p>

<pre><code>def new_value(value):
    """Encapsulation of the core treatment"""
    return 0 if (value &lt; min_value) or (value &gt; max_value) else value

new_tsdata = [[new_value(value) for value in row] for row in ts_data]
</code></pre>

<p>In python, you should seek for new objects instead of existing object modification.</p>

python list