Creating and using Ranges in Python

One of the Built-in Functions of Python3 is the range() function. This is a very usefull function that allow us to create in a very easy way lists of numbers. As you may recall we had used it in for loops. There are two ways to use this function:

  • range( number ): This way what you are telling Python to do is to give you a list that begins in 0 and has “number” elements. So if you type in your Python editor:

>>>for i in range(4):

...    print(i)

0

1

2

3

The list begins at cero and has four elements.

  • range(start, stop, step ): This way we can be a little more especific about the list that will be created. The first argument is the number at which the list will start, the second is the number where the list should stop not including, and the thrid one is the step that will be between each element of the list.

>>>for i in range(1,7,1):

...     print(i)

1

2

3

4

5

6

>>> for i in range (0,-10,-2):

...    print(i)

0

-2

-4

-6

-8

As you can see the second way is very helpfull when we have very specific lists. I found this page that explained the range function and I think it’s worth your while. 

This is my of my

CC BY 4.0 Creating and using Ranges in Python by Manuel Lepe is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.