Detect If Item is the Last in a List

Question:

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:

hello,
9,
3.14,
9

But I get this output:

hello, 
93.14, 
9

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)

Asked By: nedla2004

||

Answers:

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(',')
    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 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.

Answered By: Martijn Pieters

If you really just want to join your elements into a comma+newline-separated string then it’s easier to use str.join method:

elements = ['hello', 9, 3.14, 9]
s = ',n'.join(str(el) for el in elements)
# And you can do whatever you want with `s` string:
print(s)
Answered By: skovorodkin

If you are just looking to see if the item is last in the (or any item in any list) you could try using a function to check if an item is last in a list.

a = ['hello', 9, 3.14, 9]
def is_last(alist,choice):
        if choice == alist[-1]:
            print("Item is last in list!")
            return True
        else:
            print("Item is not last")
            return False

if is_last(a,9) == True:
    <do things>

else:
    <do other things>
Answered By: Malzyhar

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.”

Second element 9 is equal to last element, hence the comma is not printed.

The right way to check for the last element is to check the index of element :

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

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

Answered By: Shivek Khurana

While these answers may work for the specific case of the OP, I found they weren’t suitable for broader application.

Here are the methods I could think of/saw here and their respective timings.

Negative Slice Method 1

for x in urlist[:-1]:
    pass
# <- handle last item here

Negative Slice Method 2

last_item = urlist[-1]
for x in urlist:
    if x == last_item:
        pass

Enumerate Method

urlist_len = len(urlist)-1
for index, x in enumerate(urlist):
    if index == urlist_len:
        pass

Results:

┌─────────────────────────┬───────┬───────┬───────┐
│        list size        │ 10**2 │ 10**4 │ 10**8 │
├─────────────────────────┼───────┼───────┼───────┤
│ negative slice method 1 │ 2e-6  │ 2e-4  │     3 │
│ negative slice method 2 │ 1e-6  │ 1e-4  │     1 │
│ enumerate               │ 2e-6  │ 2e-4  │     2 │
└─────────────────────────┴───────┴───────┴───────┘

The negative slice method 2 is the fastest in all cases, but if you have duplicate items in your list, negative slice method 2 will give you a false positive. Also, the negative slice method requires that the sequence you are iterating over supports indexing. So, in the case of duplicate items in your list (or not index supporting sequence) use the enumerate method.

Depending on the body your loop, negative slice method 1 or 2 may result in simpler code and they are close in performance.

Answered By: Mattwmaster58

Test if the index value is the length of the list - 1

Like this:

    if item != (len(a) - 1):
        #whatever you wanted to do

    #or, if you want the index to be the last...
    if item == (len(a) - 1):
        #whatever you wanted to do
Answered By: Smilez
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.