The np.arange function

A simpler way to print a sequence of ints

"Print a sequence of ints."
import sys
import numpy as np

print(range(0, 100, 10))       #The range function returns a range object.
print(list(range(0, 100, 10))) #The list function returns a list object.
print()

print(np.arange(0, 100, 10))   #The np.arange function returns a np.ndarray object.
sys.exit(0)
range(0, 100, 10)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

[ 0 10 20 30 40 50 60 70 80 90]

A simpler way to create a sequence of floats

"Create a sequence of floats."
import sys
import numpy as np

listOfFloats = [float(i) for i in range(0, 100, 10)]   #need list comprehension
print(listOfFloats)
print()

ndarrayOfFloats = np.arange(0, 100, 10, dtype = np.float64)
print(ndarrayOfFloats)
sys.exit(0)
[0.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0]

[ 0. 10. 20. 30. 40. 50. 60. 70. 80. 90.]

Iterate through a sequence of ints.

"Iterate through a sequence of ints."
import sys
import numpy as np

for i in range(0, 100, 10):
    print(i)

print()

for i in np.arange(0, 100, 10):
    print(i)

sys.exit(0)
0
10
20
30
40
50
60
70
80
90

0
10
20
30
40
50
60
70
80
90

Things to try

  1. Print a np.ndarray with commas, so it looks like a list. The Python str function returns a string that’s easy for humans to read. The Python repr function returns a string that looks like an expression that calls the constructor function for the object. Since this string looks like a function call, it will contain the name of the function and parentheses.

    The call to astype creates and returns a np.ndarray containing 10 strings.

    "Pretty print a np.ndarray."
    import sys
    import numpy as np
    
    nd = np.arange(0, 100, 10)
    
    #Convert the np.ndarray to a string.
    print(nd)       #Means print(str(nd)).  print(np.array_str(nd)) does the same thing.
    print(repr(nd)) #print(np.array_repr(nd)) does the same thing.
    print(np.array2string(nd, separator = ", "))
    
    print()
    
    #Convert the np.ndarray to a list.
    print(list(nd))
    print(nd.tolist())
    print()
    
    #Convert the np.ndarray to the string of your choice.
    
    def string_function(nd):
        return ", ".join(nd.astype(str))    #print without the [square brackets]
    
    np.set_string_function(string_function, repr = False)
    print(nd)   #means print(str(nd))
    sys.exit(0)
    
    [ 0 10 20 30 40 50 60 70 80 90]
    array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
    [ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
    
    [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
    [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
    
    0, 10, 20, 30, 40, 50, 60, 70, 80, 90