Knowledgebase

Loops and Repetition Print

  • python, performance, guide, howto, solution, zillionkinghost, hosting, support
  • 0

Doing something repeatedly.

THE TWO KINDS

Iterating over a collection, and repeating while a condition holds.

WHICH TO USE

Iterating over a collection, almost always.

WHY

It is clearer and cannot loop forever by accident.

WHEN TO USE A CONDITIONAL LOOP

When you do not know in advance how many repetitions are needed.

WHAT TO BE CAREFUL WITH

Loops that may never end Modifying the collection you are iterating over Doing expensive work inside a loop that could be done once

THAT LAST POINT

The most common cause of slow scripts.

BREAKING OUT EARLY

Possible, and useful when you have found what you wanted.

SKIPPING AN ITERATION

Also possible, and frequently clearer than nesting a condition.

ITERATING WITH POSITIONS

Available when you need both the item and its index.

NESTED LOOPS

Multiply the work.

A loop inside a loop over large collections becomes slow quickly.

WHAT TO CONSIDER INSTEAD

Whether the work can be done in one pass.


Was this answer helpful?
Back

Are you happy with your experience? Leave us a review on Trustpilot.


Trustpilot