Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to determine if item is last item in a set

I have an arbitrary number of items in a set.

I want to do something different when I am on the last item of the set – is it possible to do so without having to find the length of the set and have a counter variable?

    for e in elements:
        if e is elements[-1]:
            json+='"%s"' % e 
            break
        json+='"%s",' % e 

The above code will work for lists, but cannot work here as splices are not supported for sets.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Leaving my comment above, you could do something like this:

s = {"A", "B", "C"}

i = iter(s)

element = next(i, None)

while element is not None:
    next_element = next(i, None)
    if next_element is None:
        # This is the last element
        print(element * 10)
    else:
        print(element)
    element = next_element

OUTPUT

B
A
CCCCCCCCCC

This is just an example how the final element could be applied a different transformation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading