Detect If Item is the Last in a List
<p>I am using Python 3, and trying to detect if an item is the last in a list, but sometimes there will repeats. This is my code:</p>

<pre><code>a = ['hello', 9, 3.14, 9]
for item in a:
    print(item, end='')
    if item != a[-1]:
        print(', ')
</code></pre>

<p>And I would like this output:</p>

<pre><code>hello,
9,
3.14,
9
</code></pre>

<p>But I get this output:</p>

<pre><code>hello, 
93.14, 
9
</code></pre>

<p>I understand why I am getting the output I do not want.
I would prefer if I could still use the loop, but I can work around them. (I would like to use this with more complicated code)</p>

<p>Rather than try and detect if you are at the last item, print the comma and newline <em>when printing the next</em> (which only requires detecting if you are at the first):</p>

<pre><code>a = ['hello', 9, 3.14, 9]
for i, item in enumerate(a):
    if i:  # print a separator if this isn't the first element
        print(',')
    print(item, end='')
print()  # last newline
</code></pre>

<p>The <code>enumerate()</code> function adds a counter to each element (see <a href="https://stackoverflow.com/questions/22171558/what-does-enumerate-mean">What does enumerate mean?</a>), and <code>if i:</code> is true for all values of the counter except <code>0</code> (the first element).</p>

<p>Or use <code>print()</code> to insert separators:</p>

<pre><code>print(*a, sep=',\n')
</code></pre>

<p>The <code>sep</code> value is inserted between each argument (<code>*a</code> applies all values in <code>a</code> as separate arguments, see <a href="http://stackoverflow.com/questions/36901/what-does-double-star-and-star-do-for-python-parameters">What does ** (double star) and * (star) do for Python parameters?</a>). This is more efficient than using <code>print(',n'.join(map(str, a)))</code> as this doesn't need to build a whole new string object first.</p>

python list python-3.x