Iterate with for loops and range #
In Python, there is a property of an object called iterable, which means it can be iterated or looped through. For example, with string data, we can iterate through each character, we can iterate through each item in a list, or iterate through each key-value pair in a dictionary. We can use a for...loop statement with these objects.
In Python, the range() function is commonly used when creating loops. The range() function generates a sequence of numbers that can be used in loops or other operations.
For example:
my_numbers = []
for i in range(5):
my_numbers.append(i)
print(my_numbers) # [0, 1, 2, 3, 4]
The first line creates an empty list called my_numbers.
for i in range(5) is a for...loop that will run five times, as specified by the argument passed to the range() function. The range function generates a sequence of integers from 0 up to (but not including) the argument passed to it.
On each iteration of the loop, the variable i is assigned the next integer in the sequence generated by the range() function.
The append method is called on my_numbers for each value of i in the loop, adding the value to the end of the list.
After the loop has finished, the list my_numbers is printed using the print() function. The output shows the list of integers from 0 to 4, as generated by the range function and appended to the list.
Exercise #
- Use
for...loopto make the listmy_numberscontains the numbers from 0 to 10.
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules