td.mart
td.mart

Reputation: 137

Function that returns a new list with values from original list that are divisible by a given number in the function parameters

I need a function that takes an array, iterates over its values and for every one of its values that is divisible by 3 without a remainder, add it to a new array. Here is what I have so far:

def exampleFour(array,num):
    temp = []
    for i in array:
       if i % num == 0:
         temp.append(i)
    return temp

print(exampleFour([3,5,9,6,7,15,24],3))

However, when I run this it only returns [3]. Can someone help me understand why?

Upvotes: 2

Views: 294

Answers (1)

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11073

Your code is returning correct result for me, but you can do it easily. Try this:

new_list = [i for i in array if i%num ==0]

Upvotes: 2

Related Questions