How can I treat the last element of the input specially, when iterating with a for loop? In particular, if there is code that should only occur "between" elements (and not "after" the last one), how can I structure the code?
Currently, I write code like so:
for i, data in enumerate(data_list):
code_that_is_done_for_every_element
if i != len(data_list) - 1:
code_that_is_done_between_elements
How can I simplify or improve this?
Most of the times it is easier (and cheaper) to make the first iteration the special case instead of the last one:
This will work for any iterable, even for those that have no
len():Apart from that, I don’t think there is a generally superior solution as it depends on what you are trying to do. For example, if you are building a string from a list, it’s naturally better to use
str.join()than using aforloop “with special case”.Using the same principle but more compact:
Looks familiar, doesn’t it? 🙂
For @ofko, and others who really need to find out if the current value of an iterable without
len()is the last one, you will need to look ahead:Then you can use it like this: