Iterating over sequences with for loops
For loops in Python are used to iterate over sequences such as lists, tuples, strings, dictionaries, sets, or any iterable object. The basic syntax is 'for item in sequence:' where 'item' takes the value of each element in the sequence sequentially. The range() function is commonly used with for loops to generate sequences of numbers. For loops can iterate over dictionaries to access keys, values, or key-value pairs using items(). Python's for loops are actually foreach loops (iterating over elements) rather than traditional C-style for loops (iterating with counter). The enumerate() function can be used when you need both the index and value during iteration. For loops are generally preferred when the number of iterations is known or when processing each element in a collection. They are more readable and less error-prone than while loops for sequence iteration, as they automatically handle advancing through the sequence and terminating when done.