473,385 Members | 1,372 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

changing the List's behaviour?

hi pythoneers

i am very annoyed by the List's index out of bouds exception
it forces me to complicate my code by adding length checking

i might be spoilt by Ruby which returns nil for not existing indices.
i want to change the List so that it returns None if the index for
accesssing list elements
is out of bound.

i am not very experienced in python, so i ask you for suggestions.

thanks in advance,
Meinrad Recheis

Jul 18 '05 #1
5 1835
On Sun, 27 Jul 2003 22:41:43 +0200, meinrad recheis wrote:
i am very annoyed by the List's index out of bouds exception
it forces me to complicate my code by adding length checking
No, it forces you to ensure your code doesn't try to access a
non-existent list element.

Or, it forces you to catch the exception and deal with it.
i want to change the List so that it returns None if the index for
accesssing list elements is out of bound.
This would prevent you from distinguishing between "the index was out of
range" and "the element at that index is the None object".
i am not very experienced in python, so i ask you for suggestions.


Take a good look at the code that is accessing non-existent index
values. Why is it doing so? Do you really want a list (ordered
collection, with a fixed set of keys) or are there cases where you want
a dict (unordered collection, arbitrary set of keys)?

--
\ "I know you believe you understood what you think I said, but I |
`\ am not sure you realize that what you heard is not what I |
_o__) meant." -- Robert J. McCloskey |
Ben Finney <http://bignose.squidly.org/>
Jul 18 '05 #2
i want to change the List so that it returns None if the index for
accesssing list elements is out of bound.


Slicing always 'works' (does not raise exception), so seq[i:i+1]
returns empty slice rather than length 1 slice if i too large. This
is a standard idiom for getting, for instance, first element of list
if there is one when there might not be.

So slice and condition off length and if 1, extract element. This has
advantage over idea above that [] is different from [None] (which you
would get is seq[i]==None).

Terry J. Reedy
Jul 18 '05 #3
meinrad recheis wrote:
i want to change the List so that it returns None if the index for
accesssing list elements
is out of bound.


If you really need it, you can write a class similar to the one below:

class DefaultList(list):
def __init__(self, sequence=[], default=None):
list.__init__(self, sequence)
self.default = default
def __getitem__(self, index):
try:
return list.__getitem__(self, index)
except IndexError:
return self.default

if __name__ == "__main__":
theList = DefaultList("abc", "?")
print theList[1]
print theList[99]

theList = DefaultList(default="X")
print theList[1]
Jul 18 '05 #4
Heather Coppersmith wrote:
class DefaultList(list):
def __init__(self, sequence=[], default=None):
list.init(self, sequence)
That's asking for trouble. That mutable default argument for
sequence is evaluated at class definition-time, and all instances
of DefaultList created without a sequence argument will end up
sharing one list.

Do this instead:

class DefaultList( list ):
def __init__( self, sequence = None, default = None ):
if sequence is None:
sequence = [ ]
list.__init__(self, sequence)


I can see the trouble only if the sequence argument is used to initialize a
member, e.g.

def __init__(self, seq=[]):
self.seq = seq # bad, multiple instances may share one list

However, in the DefaultList case, sequence is never changed.
So I don't see what can go wrong. Am I overlooking something?

- Peter
Jul 18 '05 #5
On Wed, 30 Jul 2003 17:36:12 +0200,
Peter Otten <__*******@web.de> wrote:
Heather Coppersmith wrote:
class DefaultList(list):
def __init__(self, sequence=[], default=None):
list.init(self, sequence)

That's asking for trouble. That mutable default argument for
sequence is evaluated at class definition-time, and all instances
of DefaultList created without a sequence argument will end up
sharing one list.

Do this instead:

class DefaultList( list ):
def __init__( self, sequence = None, default = None ):
if sequence is None:
sequence = [ ]
list.__init__(self, sequence)

I can see the trouble only if the sequence argument is used to initialize a
member, e.g. def __init__(self, seq=[]):
self.seq = seq # bad, multiple instances may share one list However, in the DefaultList case, sequence is never changed.
So I don't see what can go wrong. Am I overlooking something? - Peter


Oops, my mistake. ;-)

Regards,
Heather

--
Heather Coppersmith
That's not right; that's not even wrong. -- Wolfgang Pauli

Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: oom | last post by:
I am a bit of a newbie when it comes to python, when working with lists today I noticed some very odd behaviour, any suggestions welcome: Python 2.2.3 (#1, Nov 6 2003, 14:12:38) on linux2...
12
by: Tescobar | last post by:
Over one year ago somebody asked here: how to remove selected elements from list in a loop?. The answer was as follows: for( it = l.begin(); it != l.end; ) { if(...) it = l.erase(it); else...
13
by: na1paj | last post by:
here's a simple linked list program. the DeleteNode function is producing an infinit loop i think, but i can't figure out where.. #include <stdio.h> typedef struct { char *str; //str is a...
1
by: Dennis Johansson | last post by:
I have a CheckBoxList like this one: <asp:CheckBoxList id="chkReport" runat="server" DataValueField="rptID" DataTextField="RptName" Enabled="False" RepeatLayout="Flow"></asp:CheckBoxList> I...
35
by: Thierry Loiseau | last post by:
Hello all, and Happy end year 2005 ! Well, I would like to obtain a list of all JavaScript var statement, With "for...in" perharps ? That is bellow my recent test here, but the problem is...
1
by: DrJarmin | last post by:
Hello The problem is this: in the criteria for a list box I reference the parent form - and Access KEEPS changing the criteria for one that won't work. Details below: I have a couple of list...
3
by: flyfree | last post by:
>>def fooA(y): y = return y y = 3 y = 4 return y
2
by: junky_fellow | last post by:
guys, If I declare a const variable and then try to change it as follows; const int i=5; i = 10; What would be the behaviour? Should compiler give compilation error or Warning ? Or, would...
18
by: Grant Edwards | last post by:
Could whoever is responsible for the gateway that is grabbing my postings off of Usenet and e-mailing them out please fix the headers in the mail messages so that I don't get the bounce messages?...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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...

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.