Range() Function Help!


#1

I do get the fact that range() is a shortcut for generating a list, but I don’t get how the output becomes(How I think of it random)when there are three or more numbers in the parentheses of the function. This isn’t really a forum for a answer. I just want a good explanation of my problem. :frowning:


#2

The range() function allows you to get specify with the range of numbers that you want to create.

If all you want is a set of numbers from 0 to n, then you do range(n) where n - 1 is the largest number in the dataset. For example, range(10) gives you a list of [0,1,2,3,4,5,6,7,8,9].

But what if you want to start a different number? You don’t want to start your number set at 0. Maybe you want to start at 10. Python gives you a way to do that:

range(start, stop) where the start is say 10 in our example and let’s say you want to go to 20. Then you’d do range(10, 20) which gives you [10, 11, 12, 13, 14, 15, 16, 17, 18, 19].

Still with me?

Let’s say that you want to increment the numbers by say 5. So what you want is a number set that starts with 5 and goes to 30 but is only increments of 5s.

range(5, 31, 5) where the last number is the step. That will give you [5, 10, 15, 20, 25, 30].

You can do negative numbers too and if negative steps. Go check out the Python documentation as it has some good examples for you:

https://docs.python.org/2/library/functions.html#range


#3

Thanks! It really helped me!


#4

You’re welcome. range is something I wish other languages had, as it’s for handy.