Greetings, Explorer! In today's adventure, we're traversing the vast expanse of range()
and enumerate()
. These two functions will serve as your co-pilots, guiding your spaceship, the for loop, through the expansive universe of Python. We're set to delve into each function, uncovering hands-on examples and real-life applications.
Our first destination is the planet range()
. This Python function generates a sequence of numbers, which are pivotal when directing a loop a specified number of times.
The range()
function can accept three different sets of parameters:
range(stop)
: generates numbers from 0
to stop - 1
.range(start, stop)
: generates numbers from start
to stop - 1
.range(start, stop, step)
: generates numbers from start
to stop - 1
in steps of step
.The start
parameter specifies the starting point of the sequence, stop
marks the endpoint (which isn't included in the sequence), and step
is the increment amount for the sequence. By default, start
is 0
, and step
is 1
.
Let's see it in action with a simple for loop
.
Python1for i in range(5): 2 print(i)
Output:
Markdown10 21 32 43 54
The range(5)
command generates numbers from 0
to 4
.
Now, let's experiment with a different value for start
and a step
:
Python1for i in range(1, 10, 2): 2 print(i)
Output:
Markdown11 23 35 47 59
As you can see, the above code starts at 1
and goes up to 9
, but it only prints every second number due to the step
of 2
.
Our next stop is galaxy enumerate()
. This function serves as our real-time radar when voyaging through a list, as it provides both the index and value of each item. Here's how:
Python1check_points = ['start', 'midpoint', 'end'] 2 3for index, check_point in enumerate(check_points): 4 print('At index', index, 'we are at the', check_point, 'of the journey.')
Output:
Markdown1At index 0 we are at the start of the journey. 2At index 1 we are at the midpoint of the journey. 3At index 2 we are at the end of the journey.
It gives both the index (index
) and corresponding checkpoint (check_point
) in the journey.
Time to dock range()
and enumerate()
together on one spaceship! To illustrate their combined use, let's consider a group of space cadets and their corresponding IDs.
Python1cadets = ["Neo", "Trinity", "Morpheus", "Agent Smith"] 2ids = [101, 102, 103, 104] 3 4for i in range(len(cadets)): 5 print('Cadet', cadets[i], 'has id', ids[i]) 6for i, cadet in enumerate(cadets): 7 print('Cadet', cadet, 'has id', i)
Here, range(len(cadets))
creates indices for the list cadets
from 0
to len(cadets) - 1
, allowing us to access both cadets
and ids
.
Great work, Space Explorer! You've decoded the mysteries of range()
and enumerate()
, preparing yourself for a robust for
loop journey through your Python universe. Solidify your skills with some practice tasks and build confidence in your newly acquired expertise. Happy coding!