How To Create A Range Of Numbers In Python
While it looks more like a built-in function, range
is actually a class. So when you use range, you're actually passing arguments into the range
constructor.
When given a single argument, range
will use this value as the stop value. Stop refers to the end of the sequence. Keep in mind that range
sequences are not inclusive, meaning the sequence will contain numbers up to but not including the stop value.
range(stop)
Example:
list(range(10))
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Note: In order to see the numbers in the sequence, we must convert the sequence to a list.
Notice how range
assumes a start value of 0
and that the sequence contains numbers up to but not including the stop value.
As one might guess, you can also specify the start value. When two arguments are passed to the range
constructor, the first is start and the second is stop.
range(start, stop)
Example:
list(range(10, 20))
Output:
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
The default step value is 1
, but sometimes we'll want to increment by something other than 1. If provided a third argument, it will be used as the step value.
range(start, stop, step)
Example:
list(range(10, 20, 2))
Output:
[10, 12, 14, 16, 18]
Iterating over a range of numbers is easy using the Python for loop.
Example:
for x in range(5): print(x)
Output:
0 1 2 3 4
You can use the range
function to iterate a specific number of times, even when you don't need to access each element of the sequence.
Imagine we want to build a string that contains ten of a certain character.
Example:
result = '' for x in range(10): result += '#' print(result)
Output:
##########
In this example, range
provides a memory efficient way of iterating exactly ten times.
Python provides a built-in function for reversing sequences called reversed
.
Example:
list(reversed(range(10)))
Output:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
You can access indexes of a range as well as use slice notation to get a subsection of the sequence.
Example:
list(range(100)[10:20])
Output:
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
At this point, you should have a solid understanding of what the range
class is and how it's used. Do you have any questions or feedback? Let me know in the comments below.
If it's been a while since you first installed Python, it might be time to check out the latest edition: Python 3. It has plenty of cool new features from data classes to typing enhancements.
How To Create A Range Of Numbers In Python
Source: https://howchoo.com/python/python-range-function
Posted by: dickensanyted.blogspot.com
0 Response to "How To Create A Range Of Numbers In Python"
Post a Comment