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>You are not getting the expected output because in your code you say, "Hey python, print a comma if current element is not equal to last element."</p>

<p>Second element 9 is equal to last element, hence the comma is not printed.</p>

<p>The right way to check for the last element is to check the index of element :</p>

<pre><code>a = ['hello', 9, 3.14, 9]
for item in a:
    print(item, end='')
    if a.index(item) != len(a)-1: #&lt;--------- Checking for last element here
        print(', ')
</code></pre>

<p>(Also, this might throw a value error. You should check for that too.)</p>

python list python-3.x