Please help me understand the "range" function
python - How do I use a decimal step value for range()? - Stack Overflow
Understanding Range() function in python. [Level: Absolute Beginner]
How do while not loops work
EDIT: Holy cow guys, I didn't expect such a helpful community! Thanks a lot everyone, I think I get it now. Cheers!
Hi! I've been enjoying learning python through the Py4e course. However, I can't wrap my head around the range function, specifically in the section about lists. They suggest using it to traverse lists like that:
numbers = [17, 123]
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
print (numbers[i])But I'm too dumb to understand what this does. Tried reading about it in the python library, only got more confused.
-
Could someone please spell out to me the logic behind this piece of code? What exactly does range do there, and why does it enables you to use square brackets to select elements of the list?
-
Why do you need to combine it with the "len" function here to get this result?
-
Why does "print (range(len(numbers)))" return "range(0, 3)" and not "(0, 3)" or "range(0, 1, 2, 3)"?
-
The code below seems to give the same result as the earlier one, so what's the difference?for i in numbers: print (i*2)
Rather than using a decimal step directly, it's much safer to express this in terms of how many points you want. Otherwise, floating-point rounding error is likely to give you a wrong result.
Use the linspace function from the NumPy library (which isn't part of the standard library but is relatively easy to obtain). linspace takes a number of points to return, and also lets you specify whether or not to include the right endpoint:
>>> np.linspace(0,1,11)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> np.linspace(0,1,10,endpoint=False)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
If you really want to use a floating-point step value, use numpy.arange:
>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
Floating-point rounding error will cause problems, though. Here's a simple case where rounding error causes arange to produce a length-4 array when it should only produce 3 numbers:
>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])
range() can only do integers, not floating point.
Use a list comprehension instead to obtain a list of steps:
[x * 0.1 for x in range(0, 10)]
More generally, a generator comprehension minimizes memory allocations:
xs = (x * 0.1 for x in range(0, 10))
for x in xs:
print(x)