472,334 Members | 2,232 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,334 software developers and data experts.

Indexing a list, the safe way

bartonc
6,596 Expert 4TB
Whenever a function retrieves a list element outside of loop, you should wrap the reference in a try block instead of testing the length of the list (because you will probably forget to subtract one in your test, introducing a but). For example:
These are safe:
Expand|Select|Wrap|Line Numbers
  1.  
  2. # inside a loop
  3. for item in someList:
  4.     # use items from list sequentially
  5.  
  6. try:
  7.     item = someList[index]
  8. except IndexError:
  9.     # handle out-ot-range index
  10.  
  11. if index < len(someList):
  12.     item = someList[index]
  13. else:
  14.     # handle out-of-range index
  15.  
This is a bug that will give an error sometimes:
Expand|Select|Wrap|Line Numbers
  1.  
  2. if index > len(someList): # should be len(someList) - 1
  3.     # handle out-ot-range index
  4. else:
  5.     item = someList[index]
  6.  
As you can see, both the if block and the try block have the same number of lines and structure, but try reduces the number of references to someList, doesn't need to call len() and protects you from a simple mistake.
Nov 19 '06 #1
3 7174
kudos
127 Expert 100+
Hi,
its not a bug the indexing in languages like python, C, java indexes from 0 as the first. So, in a = [1,2,3] elements a[2] = 3, but is still contains 3 elements..
If I recall correctly pascal & matlab indexes from 1 (which actually is more "mathematical".

-kudos


Whenever a function retrieves a list element outside of loop, you should wrap the reference in a try block instead of testing the length of the list (because you will probably forget to subtract one in your test, introducing a but). For example:
These are safe:
Expand|Select|Wrap|Line Numbers
  1.  
  2. # inside a loop
  3. for item in someList:
  4.     # use items from list sequentially
  5.  
  6. try:
  7.     item = someList[index]
  8. except IndexError:
  9.     # handle out-ot-range index
  10.  
  11. if index < len(someList):
  12.     item = someList[index]
  13. else:
  14.     # handle out-of-range index
  15.  
This is a bug that will give an error sometimes:
Expand|Select|Wrap|Line Numbers
  1.  
  2. if index > len(someList): # should be len(someList) - 1
  3.     # handle out-ot-range index
  4. else:
  5.     item = someList[index]
  6.  
As you can see, both the if block and the try block have the same number of lines and structure, but try reduces the number of references to someList, doesn't need to call len() and protects you from a simple mistake.
Nov 19 '06 #2
bartonc
6,596 Expert 4TB
Hi,
its not a bug the indexing in languages like python, C, java indexes from 0 as the first. So, in a = [1,2,3] elements a[2] = 3, but is still contains 3 elements..
If I recall correctly pascal & matlab indexes from 1 (which actually is more "mathematical".

-kudos
But len() returns the lenght of the object which IS one greater than the index of the last item: len([1,2,3]) = 3
Nov 20 '06 #3
kudos
127 Expert 100+
yeah, I know. I guess it would make more sense if indexing started at 1, so one could get the last elements by doing a len, but for some reason indexing start at 0. I guess its just tradition, C index start at 0, so then everybody else do it too...(but its true, ALOT of bugs had been avoided we started at 1)

-kudos

But len() returns the lenght of the object which IS one greater than the index of the last item: len([1,2,3]) = 3
Nov 20 '06 #4

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

Similar topics

21
by: Hilde Roth | last post by:
This may have been asked before but I can't find it. If I have a rectangular list of lists, say, l = ,,], is there a handy syntax for retrieving...
12
by: Steven Bethard | last post by:
So I need to do something like: for i in range(len(l)): for j in range(i+1, len(l)): # do something with (l, l) where I get all pairs of...
10
by: Ishwor | last post by:
Hi all. Look at this snippet of code. >>> l = >>> l >>> l 'a' It prints the value 'a'. Fine so far :-) l ---> 'a' . l---> 'a' --> 'a'.
108
by: Bryan Olson | last post by:
The Python slice type has one method 'indices', and reportedly: This method takes a single integer argument /length/ and computes information...
6
by: Zri Man | last post by:
I'm relatively new to DB2 and was reasonably amused to see the REVERSE SCAN availability for Indexes. My assumptions are as follows: DB2/UDB...
6
by: yomgui | last post by:
Hi, I have a list of data (type A) my list can includes element of type A or a lists, these list can includes element of type A or a lists, and...
3
by: Chung Leong | last post by:
Here's the rest of the tutorial I started earlier: Aside from text within a document, Indexing Service let you search on meta information stored...
4
by: Emin | last post by:
Dear Experts, How much slower is dict indexing vs. list indexing (or indexing into a numpy array)? I realize that looking up a value in a dict...
6
by: 78ncp | last post by:
hi... how to implementation algorithm latent semantic indexing in python programming...?? thank's for daniel who answered my question before.. ...
0
by: concettolabs | last post by:
In today's business world, businesses are increasingly turning to PowerApps to develop custom business applications. PowerApps is a powerful tool...
0
better678
by: better678 | last post by:
Question: Discuss your understanding of the Java platform. Is the statement "Java is interpreted" correct? Answer: Java is an object-oriented...
0
by: CD Tom | last post by:
This happens in runtime 2013 and 2016. When a report is run and then closed a toolbar shows up and the only way to get it to go away is to right...
0
by: CD Tom | last post by:
This only shows up in access runtime. When a user select a report from my report menu when they close the report they get a menu I've called Add-ins...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.