Iteration
For Loop
The for loop allows iteration over elements in a collection (such as lists, strings, or ranges).
Iterating Over a List
Example:
Output:
Iterating Over Numbers and Calculations
Example:
Output:
Iterating Over Characters of a String
Example:
Output:
Iterating Over a Range of Numbers
Example:
Output:
Skipping Items in a List
You can use slicing to iterate over every other item in the list
Example:
Output:
While Loop
The while loop repeats a block of code as long as a given condition is True.
Example:
Output:
Iterators
An iterator allows you to traverse through a collection, such as a list, tuple, set, or string.
Once an iterator has exhausted its values, it will raise an error if you attempt to retrieve another element.
Example:
Output:
Behind the scenes, a for loop implicitly calls iter() and next() to iterate over the elements.
Range
range() generates an immutable sequence of numbers and is commonly used for looping a specific number of times in a for loop.
Syntax:
start: Starting value (inclusive)
stop: Ending value (exclusive)
step: Increment (default is 1)
Example:
Output:
The range object only stores the values for start, stop, and step, and does not hold all the numbers in memory.
Using range with For Loop
Example:
Output:
Range Slicing and Negative Indices
You can perform slicing and index lookups on range objects.
Example:
Output:
Reversing a Range
Example:
Output:
continue in Loops
The continue statement skips the current iteration and continues with the next iteration of the loop.
Example:
Output:
break in Loops
The break statement exits the loop.
Example:
Output:
else in Loops
An else block can be used with for and while loops. It will run if the loop completes normally, without hitting a break statement.
Example with for:
Output:
Example with while:
Output:
Example with break:
Enumerating over a collection with enumerate
The enumerate() function is useful when you need both the index and the value in a loop.
Example:
Output:
Using zip() to iterate over multiple collections
The zip() function allows to iterate over several collections at the same time.
Example:
Output: