473,472 Members | 2,257 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Indexing a list, the safe way

bartonc
6,596 Recognized Expert Expert
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 7955
kudos
127 Recognized Expert New Member
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 Recognized Expert Expert
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 Recognized Expert New Member
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 the ith item of every sublist? I know about for i...
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 items in a list (where I'm thinking of pairs as sets,...
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 about the extended slice that the slice object would...
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 uses B-Tree for indexing by default and is likely...
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 so on ... is there a simple way to obtain a...
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 in the files. For example, MusicArtist and...
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 should be constant time, but does anyone have a...
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.. -- View this message in context:...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.