How can I return an array from a function?

I am trying to set up a function that will append values to an array. When I try to return the array from the function instead of getting the newly appended array I just get an empty one [].

I know the rest of the code works when it is all inside one function however I have been tasked with specifically defining the values outside the function and only appending inside the function.

Is there a way to return the newly appended array in order to append to it again?

import numpy as np

arr = np.zeros(0) #setting up empty array

def append_to_array (arr, value):
    arr = np.append(arr, value) #appends value to array
    print(arr) #prints array with appended value
    return(arr)

inputs = True
while inputs:
    value = input("Enter the next number to be added to the array, 'Done' to stop the loop: ")
    if value == "Done":
        inputs = False
    else:
        append_to_array(arr, float(value))
print(value)

>Solution :

You either need to assign the returned array back to the original arr:

import numpy as np

arr = np.zeros(0) #setting up empty array

def append_to_array (arr, value):
    arr = np.append(arr, value) #appends value to array
    print(arr) #prints array with appended value
    return(arr)

inputs = True
while inputs:
    value = input("Enter the next number to be added to the array, 'Done' to stop the loop: ")
    if value == "Done":
        inputs = False
    else:
        arr = append_to_array(arr, float(value))

or use a pythons (non-numpy) arrays (a.k.a list):

arr = [] #setting up empty array

def append_to_array (arr, value):
    arr.append(value) #appends value to array
    print(arr) #prints array with appended value

inputs = True
while inputs:
    value = input("Enter the next number to be added to the array, 'Done' to stop the loop: ")
    if value == "Done":
        inputs = False
    else:
        append_to_array(arr, float(value))

Sindenote: I suggest using break:

arr = [] #setting up empty array

def append_to_array (arr, value):
    arr.append(value) #appends value to array
    print(arr) #prints array with appended value

while True:
    value = input("Enter the next number to be added to the array, 'Done' to stop the loop: ")
    if value == "Done":
        break
    append_to_array(arr, float(value))

Leave a Reply