Towards understanding One Line For loops
<p>After reading <a href="http://stackoverflow.com/questions/12920214/python-for-syntax-block-code-vs-single-line-generator-expressions">this</a> question, I have this PySpark code:</p>

<pre><code>model = KMeansModel(model.Cs[0])
first_split = split_vecs.map(lambda x: x[0])
model.computeCost(first_split)
model = KMeansModel(model.Cs[1])
second_split = split_vecs.map(lambda x: x[1])
model.computeCost(second_split)
</code></pre>

<p>Can I write this into a one-liner for loop? Or these loops are restricted in having <em>only one</em> line in their body?</p>

<p>Note: I am not looking for code-only answers, I want to learn, so please, explain. :)</p>

<hr>

<p>Here is my tragic attempt:</p>

<pre><code>model.computeCost(split) for i in range(2): # &lt;- the semicolon here doesn't feel right..Where to put the other lines?
</code></pre>

<hr>

<p>Edit:</p>

<p>Yes, I know that I can write a regular <a href="/questions/tagged/for-loop" class="post-tag" title="show questions tagged &#39;for-loop&#39;" rel="tag">for-loop</a>, but I would like to understand one-liner for loops. This is for experimenting. You see, when reading others' people code, I see them often, and I am not comfortable with them... :/</p>

<p>You could wrap the three distinct functions you have (KMeansModel,split_vec.map, and computeCost) in another function, like so:</p>

<pre><code>def master_fx(var):
    return fx_C(fx_B(fx_A(var)))
</code></pre>

<p>Now that it looks nice, you can either use list comprehension:</p>

<pre><code>[master_fx(element) for element in range(2)]
</code></pre>

<p>Or a for loop (on one or more lines -- it generally makes no difference, except in terms of readability. I say generally because I do get an error when I try to put another control structure on the same line, as in:</p>

<pre><code>for i in range(2): if i%2==0: print(i)
</code></pre>

<p>However, for readability's sake, you probably wouldn't want something like the line above anyway)</p>

<p>Probably the most important difference is that a for loop is just a control structure whereas list comprehension is a fancy kind of list over which you can define operations. That is why in an interactive interpreter such as ipython, you have to print the output (element and i in the examples above) of a for loop but not of list comprehension.</p>

python loops for-loop apache-spark pyspark