You can't always rely on for-loop mechanics to do branching.
Also, having an implied "conditional" that must be extracted by reading the head-portion of a loop is very very unreadable. I'd reject your submission on a code-review.
Instead, you should do something like below. I assume that your example is contrived, so for the sake of argument, assume I have all sorts of business cruft around mine. I.e. should_process exists because there are business rules for processing/not processing the master_list.
def should_process(master_list):
return master_list is not None and len(master_list) > 0
def main_doing_of_stuff_foo():
if not should_process(masterList):
return # Yes, this thing should be in its own method so you can do an early exit.
for item in masterList: # Yes, you should be using an iterator as well, not indexing.
print("Body goes here".)
I can't follow. The code I showed is already processing masterlist and decides if it should process masterlist[z].list2 for every z: 0..masterlist.length.
I fully agree that the code in my post is very bad, I took it from the article.
The main point is that you shouldn't rely on an implied rule that comes from the oddity of the length being 0 on a list.
If I'm looping through a list, it's because I want to loop through it and process its items. I'm going to return/skip earlier due to whatever reason, and not rely on the "logic" for processing being built into the length of the list, or whoever populates the list.
Also, having an implied "conditional" that must be extracted by reading the head-portion of a loop is very very unreadable. I'd reject your submission on a code-review.
Instead, you should do something like below. I assume that your example is contrived, so for the sake of argument, assume I have all sorts of business cruft around mine. I.e. should_process exists because there are business rules for processing/not processing the master_list.