Need Assistance?

support@tutorialshub.in

Control Flow

if, elif and else

ADVERTISEMENT
Python Free Lesson
5 min read
ADVERTISEMENT

Iterating over collections

A for loop asks an iterable for its values one at a time. Lists, tuples, strings, dictionaries, files, ranges and generators can all be iterated.

Use Python's iteration tools

Use enumerate() when you need an index and value, items() for dictionary key-value pairs and range() when a numeric sequence is actually required. Avoid manually managing an index when direct iteration is clearer.

Keep the loop body focused

If a loop contains validation, database calls, formatting and multiple nested decisions, move part of the work into named functions. This makes the algorithm easier to test and understand.

Practice: iterate over a list of products, calculate totals and print only products whose price exceeds a chosen threshold.

ADVERTISEMENT