How can I use an if-else condition inside a list comprehension to overwrite an existing list?
<p>I'm trying to multiply numbers greater than 3 by two, and subtract one from everything else. However, nothing happens to the list.
This is my code:</p>

<pre><code>lst = [1,2,3,4,5,6,7,8,9,10]

print (lst)

[x*2 if x &gt; 3 else x-1 for x in lst]     

print (lst)
</code></pre>

<p>Why aren't the contents of the <em>lst</em> variable modified by the list comprehension?</p>

<h2>List Comprehensions and Assignment</h2>

<p>You're missing an assignment. <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">List comprehensions</a> like yours don't do in-place modifications to the list elements. Instead, the expression returns a new list, so you must <em>assign</em> the result of the list comprehension expression back to a variable. For example:</p>

<pre><code>list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list = [x*2 if x &gt; 3 else x-1 for x in list]
print(list)
</code></pre>

<p>In Ruby, there are certainly methods for performing self-mutating operations, but I'm not personally aware of a Python equivalent that retains the semantics that you're trying to use here.</p>

python list-comprehension in-place