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