1

I am trying to do calculations and append variables to sublists in python using this loop:

for latLong in latLongList[:-1]:
    distance = findDistance(latLong[0], latLong[1], usrLocation[0], usrLocation[1])
    latLong.append(distance)

It is working perfectly except, it doesn't perform the operations on the last sub list and I am confused on why this is. I know I have to modify my loop definition to include that last element but I am unsure how. Any help would be greatly appreciated!

2
  • 5
    You're specifically removing last element with latLongList[:-1]. Just use latLongList.
    – utdemir
    May 4, 2015 at 18:04
  • 6
    Are you trying to reverse latLongList? That's latLongList[::-1] you're removing the last entry. May 4, 2015 at 18:05

2 Answers 2

3

If you want the last element included, loop till the last element:

for latLong in latLongList:
    distance = findDistance(latLong[0], latLong[1], usrLocation[0], usrLocation[1])
    latLong.append(distance)
1

You do not require a slice of the list, simply iterate through the entire list. Ah, while writing this it seems @Daniel has answered the question quite well. Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.