nedla2004 nedla2004 - 10 months ago 45
Python Question

Detect If Item is the Last in a List

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:

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

And I would like this output:


But I get this output:


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)

Answer Source

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

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(item, end='')
print()  # last newline

The enumerate() function adds a counter to each element (see What does enumerate mean?), and if i: is true for all values of the counter except 0 (the first element).

Or use print() to insert separators:

print(*a, sep=',\n')

The sep value is inserted between each argument (*a applies all values in a as separate arguments, see What does ** (double star) and * (star) do for Python parameters?). This is more efficient than using print(',n'.join(map(str, a))) as this doesn't need to build a whole new string object first.