Creation and use of ranges in Python

What is Python’s range() Function?

As an experienced Python developer, or even a beginner, you’ve likely heard of the Python range() function. But what does it do? In a nutshell, it generates a list of numbers, which is generally used to iterate over with for loops. There’s many use cases. Often you will want to use this when you want to perform an action X number of times, where you may or may not care about the index. Other times you may want to iterate over a list (or another iterable object), while being able to have the index available.

The range() function works a little bit differently between Python 2.x and 3.x under the hood, however the concept is the same. We’ll get to that a bit later, however.

Python’s range() Parameters

The range() function has two sets of parameters, as follows:

range(stop)

  • stop: Number of integers (whole numbers) to generate, starting from zero. eg. range(3) == [0, 1, 2].

range([start], stop[, step])

  • start: Starting number of the sequence.
  • stop: Generate numbers up to, but not including this number.
  • step: Difference between each number in the sequence.

Deja un comentario