By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,898 Members | 1,245 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,898 IT Pros & Developers. It's quick & easy.

Subtracting units in an array from themselves

P: 39
I have a list of coordinates and am trying to ouptput the distance between each coordinate into a new list.


End resulst


Thus far my strategy is to use the enumerate function to create a new array offset from the original array, and then subtract them.

Expand|Select|Wrap|Line Numbers
  1. #creates a list called dataList from and external coordinates file
  2. dataList = [[float(s) for s in item.strip().split(",")] for item in open("coordinates.txt").readlines()]
  4. #creates an empty new array
  5. new_array=[]
  7. #enumerates the list
  8. for i,points in enumerate(dataList):
  9.   x,y,z = points
  10.   x2,y2,z2 = dataList[i+1]
  11.   new_array.append((x2-x, y2-y, z2-z))
  13. print new_array
I get the following error:
File "C:\Python27\coordinate", line 9, in <module>
x2,y2,z2 = dataList[i+1]
IndexError: list index out of range

I'm new at Python and especially workining with nested lists and am stuck on where to go from here.
Can you make recommendations on how to address this? Not really sure what list index out of range refers too.
Jun 29 '11 #1
Share this Question
Share on Google+
1 Reply

Expert Mod 2.5K+
P: 2,851
It appears that you have a list of lists, and each sublist has 3 elements of type float. If you use enumerate, each sublist is processed from the first to the very last. When the last sublist is processed and you attempt to extract the next element which does not exist (dataList[i+1]), you will receive the index error. You can use range(len(dataList)-1), add a try/except block, etc. to get around the error.
Jun 29 '11 #2

Post your reply

Sign in to post your reply or Sign up for a free account.