2.5k views
0 votes
Write a function that will sum all of the numbers in a list, ignoring the non-numbers. The function should takes one parameter: a list of values (value_list) of various types. The recommended approach for this:

a. create a variable to hold the current sum and initialize it to zero.
b. use a for loop to process each element of the list.
c. test each element to see if it is an integer or a float, and, if so, add its value to the current sum.
d. return the sum at the end.

User Williamli
by
5.9k points

1 Answer

2 votes

In python 3.8:

def func(value_list):

lst = [x for x in value_list if type(x) == int or type(x) == float]

return sum(lst)

print(func(["h", "w", 32, 342.23, 'j']))

This is one solution using list comprehensions. I prefer this route because the code is concise.

def func(value_list):

total = 0

for x in value_list:

if type(x) == int or type(x) == float:

total += x

return total

print(func(["h", "w", 32, 342.23, 'j']))

This is the way as described in your problem.

User Puyol
by
6.1k points