Creation and use of ranges

--Originally published at Quirino´s Projects

When you want to get a set of the range from number ‘a’ to number ‘b’

range() Is the function you might want to use. To create it one argument is enough, we could simply do:
range(5)

This creates a set from 0 to 5

This argument is called ‘Stop’, indicates where to stop, since we have no ‘Start’ argument, python takes ‘0’ as the starting number

If we want to start from another number we need to pass two arguments to the function

range(6,22)

This creates a set from 6 to 22

Now that range is taking two parameters, the first one is ‘Start’ it defines where the range will start and the second will be ‘Stop’

The third argument the range function can take is ‘Step’ this indicates the step the range, for example

range(0,100,2)

Will create all the even numbers from 0 to 100

 

The range function can be treated like a list but its still a range object

The most common use i have found for ranges is to do something n times in an object with a for loop with the index of the object each iteration.

Example

If i wanted to work with the index of the string “Juan”

using

for i in string:

would return J u a n

Instead i could use

for i in range(len(juan))

This would return 0 1 2 3