Introduction to Range and Enumerate in For Loops

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.

Exploring the Range Function

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.

Range Function: Examples

Let's see it in action with a simple for loop.

Output:

The range(5) command generates numbers from 0 to 4.

Now, let's experiment with a different value for start and a step:

Output:

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.

Enumerate: Indexing the Elements

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:

Output:

It gives both the index (index) and corresponding checkpoint (check_point) in the journey.

Range Function: Use Case

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.

Here, range(len(cadets)) creates indices for the list cadets from 0 to len(cadets) - 1, allowing us to access both cadets and ids.

Conclusion: Mastery Check and Recap

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!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal