You have a list of strings that are numbers and you need to get a sumation of those numbers. How can you do that in Python? Below, I show you three different ways.
Example Code:
nums = [“3”, “8”, “10”, “1”]
# This will not work because the list items are strings, not integers or floats # print(sum(nums))
# A traditional way of handling this problem total = 0 for num in nums: total += int(num) print(“For loop method:”, total)
# A cool Pythonic way of handling the problem is to use a List comprehension print(“List comprehension method: “, sum([int(num) for num in nums]))
# Using the map function is probably the best way to handle this problem and also very Pythonic print(“Map method:”, sum(map(int, nums)))
Output:
For loop method: 22 List comprehension method: 22 Map method: 22
Remember map next time you need to apply a function to each element that is part of an iterable. The syntax is map(function_to_call, iterable). In our example, we called the int function for elements belonging to a list. The result was a map object that contained integer elements, which we could then use as an argument for the sum function.