2

I am very new to Python. I have a function DISTANCE(lat1, long1, lat2, long2) that calculates the distance between 2 points.

Then I have a list called POINTS, where each value is another list which contains those four values.

I would like to obtain the sum of the results of the function DISTANCE for all the values inside POINTS.

Can anybody help me with that? Thanks!

Mattie
  • 20,280
  • 7
  • 36
  • 54
andresmechali
  • 705
  • 2
  • 7
  • 18

4 Answers4

8
sum(DISTANCE(*p) for p in POINTS)

The * here is the syntax for Unpacking Argument Lists, also called the splat operator. This passes the contents of an iterable as the positional arguments to a function, so if p were [1, 2, 3, 4], DISTANCE(*p) would be the same as DISTANCE(1, 2, 3, 4).

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
4

How about:

totalDistance = sum(DISTANCE(lat1, long1, lat2, long2) for (lat1, long1, lat2, long2) in POINTS)
Alex Wilson
  • 6,690
  • 27
  • 44
4
sum([DISTANCE(*args) for args in POINTS])

What this one-liner does is use a list comprehension on POINTS, applying each item in it as a list to DISTANCE, like this:

args = [1, 2, 3, 4]
DISTANCE(*args) == DISTANCE(1, 2, 3, 4)

The call to sum takes a list itself and returns the sum of all the items within.

A side suggestion: name your functions in all lowercase. PEP 8 has a lot of good style suggestions for making readable Python code.

Mattie
  • 20,280
  • 7
  • 36
  • 54
2

use for-in loop if you're new to python:

result=[]
for item in POINTS:
    res=DISTANCE(*item)  
    result.append(res)
print(sum(result))

if you're confused about what's * here, you should read this

Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504