Re: list index out of range Error , need to fix it or ignore it

2016-02-28 Thread Oscar Benjamin
On 27 February 2016 at 16:50, Ganesh Pal  wrote:
> Iam on python 2.6 and Linux , I need  input on the below program ,
> here is the spinet of my program

It would be much better if you presented a complete program here.
Otherwise the missing parts will confuse people. See:
http://sscce.org/

> filename='/tmp2/2.txt'
>
> def check_file():
> """
>  Run the command parallel on all the machines , if there is a
> file named /tmp/file2.txt  extract file2.txt
>
> """
> global filename
> baddr = ''
> cmd = ("run_al_paral 'ls -al %s'" % (filename))
> print(cmd)
> stdout, stderr, exitcode = run(cmd)
> print(stdout)
> lines = stdout.strip().split('\n')

.splitlines() is more portable than .split('\n') as it handles '\r' as well.

> print(lines)

There are a few problems with the code below:

> for line in lines:
> if 'exited' in lines:
> continue
>
> file = lines[0].split()[9][6:]

Okay so you're skipping lines that contain the text "exited" in order
to find the line you want. That's fine except that you then try to
access the line you've found as lines[0] rather than line (singular).
This means that although your loop continues when the line contains
"exited" you're still accessing the first element of lines (which may
be one of the ones that contains "exited") in any case. I think that
you meant line rather than lines[0] here.

You're assuming that lines has at least one element. Otherwise
lines[0] would give IndexError. This won't raise IndexError since the
line of code "file = ..." is only executed inside the body of the for
loop which means that if lines is empty then execution doesn't reach
this point. I don't think that that was your intention though as
really it should be line rather than lines[0].

You're then assuming that lines[0].split() (which should really be
line.split())) has at least 10 elements since you ask for
lines[0].split()[9]. This will raise IndexError if .split() returnd
fewer than 10 substrings. This is most likely the IndexError that you
get. Your incorrect use of line rather than lines[0] means you're
reading one of the lines that contains "exited" and so when you call
.split() on that it gives fewer than 10 elements and so the last index
in lines[0].split()[9] raises IndexError.

> break
> print file

Here you're assuming that lines contains at least one string that does
not contain the substring "exited". Otherwise this line will leas to a
NameError since the name file is not bound to anything unless the
"file=" line is executed.

> return file
>
> def main():
> functions = [check_file]
> for func in functions:
> try:
> func()
> except Exception as e:
> return False

Here you've crippled Python's ability to give quite useful error
messages. Replace the above with:

def main():
check_file()

and then Python will print a helpful error message. More than that if
you learn to use a debugger you can hook into the exact moment where
an *uncaught* error is raised. Since you catch the error that won't be
possible. The traceback that Python prints *if you don't catch the
error* contains useful information about the problem. Even if you
don't understand that information other people do so if you post it
here then you can get much better help. It shows the line at which the
error occurred and has more description than simply IndexError.

If you remove the try/except you can then use pdb. Just rerun your code as

$ python -m pdb myscript.py

Type "c" (and hit enter) to "continue". This will run your script
right up to the point of the uncaught exception and then hook you into
a debugger at the moment the exception was raised. You can then use
"l" to show the surrounding code. Use "p file" to show the value of
for example the file variable if that seems to be the problem.

--
Oscar
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: list index out of range Error , need to fix it or ignore it

2016-02-28 Thread Steven D'Aprano
On Sun, 28 Feb 2016 03:50 am, Ganesh Pal wrote:

> Iam on python 2.6 and Linux , I need  input on the below program ,
> here is the spinet of my program
> 
> 
> filename='/tmp2/2.txt'
> 
> def check_file():
> """
>  Run the command parallel on all the machines , if there is a
> file named /tmp/file2.txt  extract file2.txt
> 
> """
> global filename

Since filename is never assigned to inside the function, you don't need to
declare it global.

But better is to make the filename an argument of the function. That will
allow you to check for different files, not always the same one.


> baddr = ''

Not used. Get rid of it.


> cmd = ("run_al_paral 'ls -al %s'" % (filename))
> print(cmd)
> stdout, stderr, exitcode = run(cmd)

run is not defined.


> print(stdout)
> lines = stdout.strip().split('\n')
> print(lines)
> for line in lines:
> if 'exited' in lines:
> continue
> file = lines[0].split()[9][6:]
> break
> print file
> return file
> 
> def main():
> functions = [check_file]
> for func in functions:
> try:
> func()
> except Exception as e:
> return False

Why do you bother to return False? Nothing checks the return value of
main().

As far as the try...except block, please read this:

https://realpython.com/blog/python/the-most-diabolical-python-antipattern/



> if __name__ == '__main__':
>   main()
> 
> 
> 
> 1.If the file is present in any one of the machine the program works
> fine , example if the file is in machine4 it works fine,
> 
> 
> machine-4# touch /tmp2/2.txt
> machine-4# python c_4.py
> run_al_parall 'ls -al /tmp2/2.txt'
> machine-4: -rw-r--r-- 1 root  wheel  0 Feb 27 08:15 /tmp2/2.txt
> gpal-machine-2 exited with status 1
> gpal-machine-5 exited with status 1
> gpal-machine-3 exited with status 1
> gpal-machine-1 exited with status 1

You really should get out of the bad habit of running code as root. Once day
you will accidentally have a bug in your code that will do something it
shouldn't do (like delete the root file system) and leave your machine
unusable.

You should create a user with the minimum privileges needed to get the work
done. At the very least, you should TEST your code while running as an
unprivileged user. It is very dangerous to run buggy code as root. Who
knows what it will do?


> 2. But if the file is not present we get index out of range error , do
> we need to fix this or its expected ? or its ok.

Of course you need to fix it.

There's no way of telling where that error occurs or why it is being
printed.




-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: list index out of range Error , need to fix it or ignore it

2016-02-28 Thread Ganesh Pal
>>
> what is run(...)
>
The run (_ is a wrapper it uses suprocess.Popen and returns  stdout
,error and extitcod e

> not a good idea to have catchall exception
how to fix this ?

>
>> > return False
>> > if __name__ == '__main__':
>> >   main()
>> >
>> --
>>
> copy and paste your traceback
>

I get  " ERROR:root:list index out of range" error  if the file  is
not found in any of the machine , I dont have a trackback back


def check_file():
"""
 

   Run the command parallel on all the machines , if there is a
file named /tmp/file2.txt  extract file2.txt

"""
global filename
file = ''
cmd = ("run_al_paral 'ls -al %s'" % (filename))
print(cmd)
stdout, stderr, exitcode = run(cmd)
print(stdout)
lines = stdout.strip().split('\n')
print(lines)
for line in lines:
if 'exited' in lines:
continue

file = lines[0].split()[9][6:]
break
print file
return file

def main():
functions = [check_file]
for func in functions:
try:
func()
except Exception as e:
return False
if __name__ == '__main__':
  main()














1. But if the file is not present we get index out of range error , do
we need to fix this or its expected ? or its ok.

machine-4# python c_4.py
isi_for_array 'ls -al /tmp2/2.txt'
machine-2 exited with status 1
machine-1 exited with status 1
machine-4 exited with status 1
machine-5 exited with status 1
machine-3 exited with status 1

['machine-2 exited with status 1', 'machine-1 exited with status 1',
'machine-4 exited with status 1', 'machine-5 exited with status 1',
'machine-3 exited with status 1']
ERROR:root:list index out of range

3. Any other tips to improve the program
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: list index out of range Error , need to fix it or ignore it

2016-02-27 Thread Joel Goldstick
On Sat, Feb 27, 2016 at 12:01 PM, Ganesh Pal  wrote:

> changed baddr="" to file ="" in the example program , sorry for the typo
>
> > filename='/tmp2/2.txt'
> >
> > def check_file():
>

don't use global filename.  just pass filename into check_file
def check_file(filename):

> > """
> >  Run the command parallel on all the machines , if there is a
> > file named /tmp/file2.txt  extract file2.txt
> >
> > """
> > global filename
> > file = ''
> > cmd = ("run_al_paral 'ls -al %s'" % (filename))
> > print(cmd)
> > stdout, stderr, exitcode = run(cmd)
>
what is run(...)

> > print(stdout)
> > lines = stdout.strip().split('\n')
> > print(lines)
> > for line in lines:
> > if 'exited' in lines:
> > continue
> >
> > file = lines[0].split()[9][6:]
> > break
> > print file
> > return file
> >
> > def main():
> > functions = [check_file]
> > for func in functions:
> > try:
> > func()
> > except Exception as e:
>
not a good idea to have catchall exception

> > return False
> > if __name__ == '__main__':
> >   main()
> >
> --
>
copy and paste your traceback

> https://mail.python.org/mailman/listinfo/python-list
>



-- 
Joel Goldstick
http://joelgoldstick.com/ 
http://cc-baseballstats.info/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: list index out of range Error , need to fix it or ignore it

2016-02-27 Thread Ganesh Pal
changed baddr="" to file ="" in the example program , sorry for the typo

> filename='/tmp2/2.txt'
>
> def check_file():
> """
>  Run the command parallel on all the machines , if there is a
> file named /tmp/file2.txt  extract file2.txt
>
> """
> global filename
> file = ''
> cmd = ("run_al_paral 'ls -al %s'" % (filename))
> print(cmd)
> stdout, stderr, exitcode = run(cmd)
> print(stdout)
> lines = stdout.strip().split('\n')
> print(lines)
> for line in lines:
> if 'exited' in lines:
> continue
>
> file = lines[0].split()[9][6:]
> break
> print file
> return file
>
> def main():
> functions = [check_file]
> for func in functions:
> try:
> func()
> except Exception as e:
> return False
> if __name__ == '__main__':
>   main()
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: List index out of range, but list has enough elements

2010-11-09 Thread Stefan Behnel

Costin Gamenț, 09.11.2010 10:24:

Hi, I am trying to read a string as csv, but I encountered an odd
problem. Here's my code:

csvfile = csv.reader(datastr.split('\n'), delimiter=';')
r = ''
for i in csvfile:
for j in i:
print j
print i[0]

the print j statement works, but print i[0] returns IndexError:
list index out of range. Am I missing something?


Are you sure the output you get from the print j is from the same loop 
iteration as the print i[0]? Try adding i to the output.


Stefan

--
http://mail.python.org/mailman/listinfo/python-list


Re: List index out of range, but list has enough elements

2010-11-09 Thread Peter Otten
Costin Gamenț wrote:

 Hi, I am trying to read a string as csv, but I encountered an odd
 problem. Here's my code:
 
 csvfile = csv.reader(datastr.split('\n'), delimiter=';')
 r = ''
 for i in csvfile:
 for j in i:
 print j
 print i[0]
 
 the print j statement works, but print i[0] returns IndexError:
 list index out of range. Am I missing something?

Change

print i[0]

to

print i

You'll see that there are empty rows in your data. You cannot detect these 
rows with

for j in i:
   print j

because you get zero iterations, i. e. the 

print j 

statement is never executed for these rows.

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List index out of range, but list has enough elements

2010-11-09 Thread Costin Gamenț
Thank you for your timely response. Yes, I am sure i and j are
from the same iteration. I should point out that i actually has 8
elements and that str(i) gives a nice printout.

On Tue, Nov 9, 2010 at 11:33 AM, Stefan Behnel stefan...@behnel.de wrote:
 Costin Gamenț, 09.11.2010 10:24:

 Hi, I am trying to read a string as csv, but I encountered an odd
 problem. Here's my code:

        csvfile = csv.reader(datastr.split('\n'), delimiter=';')
        r = ''
        for i in csvfile:
                for j in i:
                        print j
                print i[0]

 the print j statement works, but print i[0] returns IndexError:
 list index out of range. Am I missing something?

 Are you sure the output you get from the print j is from the same loop
 iteration as the print i[0]? Try adding i to the output.

 Stefan

 --
 http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List index out of range, but list has enough elements

2010-11-09 Thread Nitin Pawar
You may want to try a spilt if you are getting 8 different elements then it
will give you a list of those elements

On Tue, Nov 9, 2010 at 3:21 PM, Costin Gamenț costin.gam...@gmail.comwrote:

 Thank you for your timely response. Yes, I am sure i and j are
 from the same iteration. I should point out that i actually has 8
 elements and that str(i) gives a nice printout.

 On Tue, Nov 9, 2010 at 11:33 AM, Stefan Behnel stefan...@behnel.de
 wrote:
  Costin Gamenț, 09.11.2010 10:24:
 
  Hi, I am trying to read a string as csv, but I encountered an odd
  problem. Here's my code:
 
 csvfile = csv.reader(datastr.split('\n'), delimiter=';')
 r = ''
 for i in csvfile:
 for j in i:
 print j
 print i[0]
 
  the print j statement works, but print i[0] returns IndexError:
  list index out of range. Am I missing something?
 
  Are you sure the output you get from the print j is from the same loop
  iteration as the print i[0]? Try adding i to the output.
 
  Stefan
 
  --
  http://mail.python.org/mailman/listinfo/python-list
 
 --
 http://mail.python.org/mailman/listinfo/python-list




-- 
Nitin Pawar
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List index out of range, but list has enough elements

2010-11-09 Thread Costin Gamenț
Thank you all for your interest in my problem. As Peter pointed out,
there was one row with zero elements in it and that's where my problem
was (of course it was the very last row, hence my confidence I have
good data).

Have a nice one,
Costin

On Tue, Nov 9, 2010 at 12:02 PM, Nitin Pawar nitinpawar...@gmail.com wrote:
 You may want to try a spilt if you are getting 8 different elements then it
 will give you a list of those elements

 On Tue, Nov 9, 2010 at 3:21 PM, Costin Gamenț costin.gam...@gmail.com
 wrote:

 Thank you for your timely response. Yes, I am sure i and j are
 from the same iteration. I should point out that i actually has 8
 elements and that str(i) gives a nice printout.

 On Tue, Nov 9, 2010 at 11:33 AM, Stefan Behnel stefan...@behnel.de
 wrote:
  Costin Gamenț, 09.11.2010 10:24:
 
  Hi, I am trying to read a string as csv, but I encountered an odd
  problem. Here's my code:
 
         csvfile = csv.reader(datastr.split('\n'), delimiter=';')
         r = ''
         for i in csvfile:
                 for j in i:
                         print j
                 print i[0]
 
  the print j statement works, but print i[0] returns IndexError:
  list index out of range. Am I missing something?
 
  Are you sure the output you get from the print j is from the same loop
  iteration as the print i[0]? Try adding i to the output.
 
  Stefan
 
  --
  http://mail.python.org/mailman/listinfo/python-list
 
 --
 http://mail.python.org/mailman/listinfo/python-list



 --
 Nitin Pawar


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List index out of range, but list has enough elements

2010-11-09 Thread Stefan Behnel

[rearranged the responses in the right order]

Costin Gamenț, 09.11.2010 11:44:

On Tue, Nov 9, 2010 at 3:21 PM, Costin Gamenț wrote:

On Tue, Nov 9, 2010 at 11:33 AM, Stefan Behnel wrote:

Costin Gamenț, 09.11.2010 10:24:

Hi, I am trying to read a string as csv, but I encountered an odd
problem. Here's my code:

csvfile = csv.reader(datastr.split('\n'), delimiter=';')
r = ''
for i in csvfile:
for j in i:
print j
print i[0]

the print j statement works, but print i[0] returns IndexError:
list index out of range. Am I missing something?


Are you sure the output you get from the print j is from the same loop
iteration as the print i[0]? Try adding i to the output.


Thank you for your timely response. Yes, I am sure i and j are
from the same iteration. I should point out that i actually has 8
elements and that str(i) gives a nice printout.


Thank you all for your interest in my problem. As Peter pointed out,
there was one row with zero elements in it and that's where my problem
was (of course it was the very last row, hence my confidence I have
good data).


A classic don't be sure before you've tested. ;-)

Stefan

--
http://mail.python.org/mailman/listinfo/python-list


Re: list index out of range

2008-05-13 Thread Mike Kent
On May 13, 2:39 pm, Georgy Panterov [EMAIL PROTECTED] wrote:

 def deal_hand(deck):
 HAND=[]
 for _ in range(2):
 i=random.randint(0,len(deck)) #produces a random card from the deck
  ^ Here i can be from 0 thru (the number of cards in the
deck).

 HAND.append(deck[i]) # appends the card to the players' hand list
   ^ Here you index into the deck to get a
card.  The legal indexes are 0 thru (number of cards in the deck - 1)
 What happens if i is (the number of cards
in the deck)?

 deck.remove(deck[i]) #removes the card from the deck
 return HAND

--
http://mail.python.org/mailman/listinfo/python-list


Re: list index out of range

2008-05-13 Thread inhahe
random.randint(x,y) returns a random integer between _and including_ x and 
y, so randint(0, len(deck)) might return len(deck) and since python's 
indices start at 0, the maximum index is len(deck)-1.

rather than using randint(0,len(deck)-1) you could just do
card = random.choice(deck)
HAND.append(card)
deck.remove(card)

although it would be more efficient to do remove card by index which then 
gets us back to using randint, like this

i = random.randint(0, len(deck)-1)
HAND.append(deck[i])
del deck[i]

but i guess speed probably isn't a big factor here

also you could have done
i=random.randint(0, len(deck)-1)
HAND.append(deck.pop(i))






Georgy Panterov [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
I am a relatively new python user. I am writing an economic simulation of a 
card-game. The simulation runs fine for a few iteration but then it gives an 
error of list index out of range.

The strange thing is that it will sometimes run for 10 iterations sometimes 
for only a few and sometimes won't run at all (seemingly arbitrary).
Here is some of the code:

for _ in range(100):
handA=deal_hand(DECK) #deals 2 'hole' cards from a DECK
handB=deal_hand(DECK)
print handA
print handB
deal_flop(handA,handB,DECK) #appends 3 cards to handA and handB
deal_current(handA,handB,DECK) #appends one more card
deal_rake(handA,handB,DECK) #appends one more card
DECK.extend(list(set(handA+handB))) #returns the cards to the DECK
print winner(handA,handB) #returns 0-draw 1 -playerA win, 2-playerB win

The error message is :

['08C', '10H']
['07S', '03C']

['06C', '02H']
['04D', '12S']

['11H', '14S']
['06S', '04S']


Traceback (most recent call last):
  File G:\Other Stuff\POKER4.py, line 267, in module
handB=deal_hand(DECK)
  File G:\Other Stuff\POKER4.py, line 13, in deal_hand
HAND.append(deck[i])
IndexError: list index out of range

In this case it ran 3 times. It will sometimes run for up to 9-10 times. It 
seems to be arbitrary but I can't get it to run more than 12 times.

Here is the code for the --deal_***-- functions:

def deal_hand(deck):
HAND=[]
for _ in range(2):
i=random.randint(0,len(deck)) #produces a random card from the deck
HAND.append(deck[i]) # appends the card to the players' hand list
deck.remove(deck[i]) #removes the card from the deck
return HAND

def deal_flop(hand1,hand2,deck):
for _ in range(3):
i=random.randint(0,len(deck))

hand1.append(deck[i])
hand2.append(deck[i])
deck.remove(deck[i])

I would appreciate any help with this
Thanks
George


Send instant messages to your online friends http://uk.messenger.yahoo.com 


--
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-05 Thread TheFlyingDutchman


 I explain it by noting that list.index and dict.get serve totally
 different purposes. The former returns the index given a value; the
 latter returns a value given a key.

And the former raises an exception if the value is not found, while
the latter returns None if the value is not found.


 There are many areas of poor symmetry in the language and libraries;
 it isn't particularly clever or difficult to find them if one
 looks. Doing so doesn't appear to illustrate any point I see relevant
 in this thread.

It has been stated in this thread, that in Python, exceptions are used
differently than in other languages. Rather than just use them for
catastrophic errors that can't be dealt with, Python raises exceptions
on routine and survivable situations such as an item not found in a
list. It was mentioned that an exception is more Pythonic than
returning a not found value.

Someone pointed out that find() in str was a contradiction to this
since it doesn't throw an exception but returns a not found value,
and the response was that it was believed that find() would be removed
from the language (if so, it does not currently show up on the
removed list as has_key() and a few others do -
http://docs.python.org/dev/3.0/whatsnew/3.0.html) and was only there
for historical reasons.

I don't believe the poster was trying to illustrate a point already
mentioned in the thread, but to give a contradiction to statements in
the thread. He was asking the question - why doesn't dict.get() throw
an exception on not found if that is the Pythonic way?


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-05 Thread Steve Holden
TheFlyingDutchman wrote:
 I explain it by noting that list.index and dict.get serve totally
 different purposes. The former returns the index given a value; the
 latter returns a value given a key.
 
 And the former raises an exception if the value is not found, while
 the latter returns None if the value is not found.
 
 There are many areas of poor symmetry in the language and libraries;
 it isn't particularly clever or difficult to find them if one
 looks. Doing so doesn't appear to illustrate any point I see relevant
 in this thread.
 
 It has been stated in this thread, that in Python, exceptions are used
 differently than in other languages. Rather than just use them for
 catastrophic errors that can't be dealt with, Python raises exceptions
 on routine and survivable situations such as an item not found in a
 list. It was mentioned that an exception is more Pythonic than
 returning a not found value.
 
 Someone pointed out that find() in str was a contradiction to this
 since it doesn't throw an exception but returns a not found value,
 and the response was that it was believed that find() would be removed
 from the language (if so, it does not currently show up on the
 removed list as has_key() and a few others do -
 http://docs.python.org/dev/3.0/whatsnew/3.0.html) and was only there
 for historical reasons.
 
 I don't believe the poster was trying to illustrate a point already
 mentioned in the thread, but to give a contradiction to statements in
 the thread. He was asking the question - why doesn't dict.get() throw
 an exception on not found if that is the Pythonic way?
 
 
Because it's an explicit short-cut for a frequently-required paradigm. 
It's effectively an extension to dict indexing - which, you will recall, 
*does* raise an exception when the key is not found. Does *everything* 
have to raise such an exception?

There's no requirement for Python to be 100% consistent in its 
application of a principle, but on the whole it is reasonably consistent.

For Pete's sake stop wasting your time and go do some programming. 
Nothing will ever be perfect, not even Python ;-)

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-04 Thread Jason
On Aug 30, 1:27 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 On Thu, 30 Aug 2007 17:09:36 +1000, Ben Finney wrote:
  [EMAIL PROTECTED] writes:

  What's with the index() function of lists throwing an exception on not
  found?

  It's letting you know that the item isn't in the list. There's no
  sensible return value from an index function in that condition.

 What about -1?  C programmers do this all the time.  :-)

 Ciao,
 Marc 'BlackJack' Rintsch

As other people pointed out, C doesn't have exceptions, so a C
programmer must make an in/out parameter to indicate an error, or have
a special return value.  In Python, you're most often searching the
list for an object which is in the list, so the lack of the object is
an exceptional condition.  You can certain check with the in
operator beforehand to avoid the exception.  You may also subclass a
list and override the index method, or write a standalone function to
catch the exception and change its value.

The reason why the exception is more Pythonic is that the return value
is always a guaranteed good index into the list.  Any errors
(including calling .index() on a non-list instance that doesn't have
a .index method) are exceptional, and should probably follow a very
different code path.

Returning -1 is not a good return value to indicate an error.  After
all, -1 is a valid index in most Python lists.  (Negative numbers
index from the tail of the list.)

  --Jason

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-04 Thread Campbell Barton
Jason wrote:
 On Aug 30, 1:27 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 On Thu, 30 Aug 2007 17:09:36 +1000, Ben Finney wrote:
 [EMAIL PROTECTED] writes:
 What's with the index() function of lists throwing an exception on not
 found?
 It's letting you know that the item isn't in the list. There's no
 sensible return value from an index function in that condition.
 What about -1?  C programmers do this all the time.  :-)

 Ciao,
 Marc 'BlackJack' Rintsch
 
 As other people pointed out, C doesn't have exceptions, so a C
 programmer must make an in/out parameter to indicate an error, or have
 a special return value.  In Python, you're most often searching the
 list for an object which is in the list, so the lack of the object is
 an exceptional condition.  You can certain check with the in
 operator beforehand to avoid the exception.  You may also subclass a
 list and override the index method, or write a standalone function to
 catch the exception and change its value.
 
 The reason why the exception is more Pythonic is that the return value
 is always a guaranteed good index into the list.  Any errors
 (including calling .index() on a non-list instance that doesn't have
 a .index method) are exceptional, and should probably follow a very
 different code path.
 
 Returning -1 is not a good return value to indicate an error.  After
 all, -1 is a valid index in most Python lists.  (Negative numbers
 index from the tail of the list.)
 
   --Jason

Agree in general tho its a bit inconsistent how...

string.find(val)

...can return -1 but .index() cant, though the inconsistency is probably 
with string since most other areas of the py api raise errors in cases 
like this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-04 Thread Neil Cerutti
On 2007-09-04, Campbell Barton [EMAIL PROTECTED] wrote:
 Jason wrote:
 Returning -1 is not a good return value to indicate an error.
 After all, -1 is a valid index in most Python lists.
 (Negative numbers index from the tail of the list.)

 Agree in general tho its a bit inconsistent how...

 string.find(val)

 ...can return -1 but .index() cant, though the inconsistency is
 probably with string since most other areas of the py api raise
 errors in cases like this.

The two functions have different ranges, but also different
domains.

sequence.index 
  domain: any item '==' to an item in sequence
  range: All non-negative indexes of sequence

string.find 
  domain: any string
  range: -1 for not found, and all non-negative indexes of string.

If you want to search for subsequences in a sequence, a la
string.find, you can use something like (what I naively assume
will be a maximally efficent):

def find(seq, subseq):
 Find a subsequence of seq in seq, and return its index. Return -1 if
subseq is not found.

 seq = [0, 1, 2, 3, 4, 5]
 find(seq, [0, 1, 2])
0
 find(seq, [])
0
 find(seq, [3, 4])
3
 find(seq, [3, 2])
-1
 find(seq, [5, 6])
-1
 find(seq, [3])
3
 find(seq, [0, 2])
-1


i = 0
j = 0
while i  len(seq) and j  len(subseq):
if seq[i] == subseq[j]: 
j += 1
else:
j = 0
i += 1
if j == len(subseq): return i - j
else: return -1

It's probable that a simpler implementation using slice
operations will be faster for shortish lengths of subseq. It was
certainly easier to get it working correctly. ;)

def find(seq, subseq):
  for i, j in itertools.izip(xrange(len(seq)-len(subseq)),
 xrange(len(subseq), len(seq))):
if subseq == seq[i:j]:
  return i
  return -1

-- 
Neil Cerutti
I pulled away from the side of the road, glanced at my mother-in-law and
headed over the embankment. --Insurance Claim Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-04 Thread Lawrence D'Oliveiro
In message [EMAIL PROTECTED], Jason
wrote:

 The reason why the exception is more Pythonic is that the return value
 is always a guaranteed good index into the list.

How do you explain dict.get, then?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-04 Thread Ben Finney
Lawrence D'Oliveiro [EMAIL PROTECTED] writes:

 In message [EMAIL PROTECTED],
 Jason wrote:
 
  The reason why the exception is more Pythonic is that the return
  value is always a guaranteed good index into the list.
 
 How do you explain dict.get, then?

I explain it by noting that list.index and dict.get serve totally
different purposes. The former returns the index given a value; the
latter returns a value given a key.

There are many areas of poor symmetry in the language and libraries;
it isn't particularly clever or difficult to find them if one
looks. Doing so doesn't appear to illustrate any point I see relevant
in this thread.

-- 
 \ If you're a horse, and someone gets on you, and falls off, and |
  `\  then gets right back on you, I think you should buck him off |
_o__) right away.  -- Jack Handey |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-04 Thread Alex Martelli
Neil Cerutti [EMAIL PROTECTED] wrote:

 It's probable that a simpler implementation using slice
 operations will be faster for shortish lengths of subseq. It was
 certainly easier to get it working correctly. ;)
 
 def find(seq, subseq):
   for i, j in itertools.izip(xrange(len(seq)-len(subseq)),
  xrange(len(subseq), len(seq))):
 if subseq == seq[i:j]:
   return i
   return -1

Simpler yet (though maybe slower!-):

def find(seq, subseq):
L = len(subseq)
for i in xrange(0, len(seq)-L):
if subseq == seq[i:i+L]: return i
return -1

also worth trying (may be faster in some cases, e.g. when the first item
of the subsequence occurs rarely in the sequence):

def find(seq, subseq):
L = len(subseq)
firstitem = subseq[0]
end = len(seq) - len(subseq)
i = -1
while 1:
try: i = seq.index(firstitem, i+1, end)
except ValueError: return -1
if subseq == seq[i:i+L]: return i

For particularly long sequences (with hashable items) it might even be
worth trying variants of Boyer-Moore, Horspool, or Knuth-Morris-Pratt;
while these search algorithms are mostly intended for text strings,
since you need tables indexed by the item values, using dicts for such
tables might yet be feasible (however, the program won't be quite that
simple).  Benchmarking of various possibilities on typical input data
for your application is recommended, as performance may vary!


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-03 Thread Thorsten Kampe
* Terry Reedy (Fri, 31 Aug 2007 02:28:36 -0400)
 Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 | On Thu, 30 Aug 2007 17:09:36 +1000, Ben Finney wrote:
 |  [EMAIL PROTECTED] writes:
 |  What's with the index() function of lists throwing an exception on not
 |  found?
 | 
 |  It's letting you know that the item isn't in the list. There's no
 |  sensible return value from an index function in that condition.
 |
 | What about -1?  C programmers do this all the time.  :-)
 
 Because they do not have exceptions. 

They have plenty of - but they can't catch them :)

Thorsten
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-03 Thread Thorsten Kampe
* Ben Finney (Thu, 30 Aug 2007 18:02:15 +1000)
 Bruno Desthuilliers [EMAIL PROTECTED] writes:
  What's with using your brain instead of whining ?
 
 Now now, no need for snappiness.

Actually there was. The OP's claim
| There are a million situations where you can have an item not be in
| a list and it is not an exception situation.

...is just plain nonsense. zzbbaadd neither does understand exceptions 
nor what they are used for in Python. An item not being in a list is 
an exception situation /by definition/.

Thorsten
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-03 Thread Ben Finney
Thorsten Kampe [EMAIL PROTECTED] writes:

 * Ben Finney (Thu, 30 Aug 2007 18:02:15 +1000)
  Bruno Desthuilliers [EMAIL PROTECTED] writes:
   What's with using your brain instead of whining ?
  
  Now now, no need for snappiness.
 
 Actually there was. The OP's claim [...] ...is just plain nonsense.

Which was pointed out in several ways without snapping. Hence the part
of my response you omitted.

Ben Finney wrote:

 If you don't feel a constructive response is merited, please ignore.

There's no need to fuel flames with content-free flaming, and Bruno
agreed with that when it was pointed out. If one doesn't have the time
or inclination to post a constructive response, not responding at all
is better than flaming.

The Python community is remarkable for its low level of flaming and
high level of content in this forum, even in response to poor
attitudes and cluelessness. I'd like it to remain that way.

-- 
 \  I don't like country music, but I don't mean to denigrate |
  `\  those who do. And for the people who like country music, |
_o__) denigrate means 'put down'.  -- Bob Newhart |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-03 Thread TheFlyingDutchman


 Actually there was. The OP's claim
 | There are a million situations where you can have an item not be in
 | a list and it is not an exception situation.

 ...is just plain nonsense. zzbbaadd neither does understand exceptions
 nor what they are used for in Python. An item not being in a list is
 an exception situation /by definition/.

It won't be /by definition/ in my fork of Python 3, which I am pleased
to announce now, is called Python 3.01 while in development, and will
be known as Python 3000 or Python 3K when it gets to a productional
release. So in regard to Python 3000, your statement will be plain
nonsense.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-03 Thread Carsten Haese
On Mon, 03 Sep 2007 19:56:04 -0700, TheFlyingDutchman wrote
 [...] my fork of Python 3, which I am 
 pleased to announce now, is called Python 3.01 while in development, 
 and will be known as Python 3000 or Python 3K when it gets to a productional
 release.

I hope you're joking.

-Carsten

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-02 Thread Zentrader
On Aug 30, 11:23 am, [EMAIL PROTECTED] wrote:
 Neil, Steve,

 Thanks for the responses on sets. I have not used them before and was
 not even aware Python had them. I will try them out.

And if there weren't sets you would still not use find or index but a
brute force method or dictionaries
for each in dir_a_list :
   if each not in dir_b_list :
  print each, not in dir_b

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-02 Thread Francesco Guerrieri
On 9/2/07, Zentrader [EMAIL PROTECTED] wrote:

 On Aug 30, 11:23 am, [EMAIL PROTECTED] wrote:
  Neil, Steve,
 
  Thanks for the responses on sets. I have not used them before and was
  not even aware Python had them. I will try them out.

 And if there weren't sets you would still not use find or index but a
 brute force method or dictionaries
 for each in dir_a_list :
if each not in dir_b_list :
   print each, not in dir_b



This is O(N_a * N_b)... unless the list are always small, it's definitely
better (if one is decided not to use sets) to use dictionaries :-)


bye
francesco
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: list index()

2007-09-01 Thread Hendrik van Rooyen
 Erik Max Francis ma...e.com wrote:


 Hendrik van Rooyen wrote:
 
  weird this - maybe a native English speaker can comment - 
  when I pronounce what fishermen do - it rhymes with roll,
  but when I am talking about the thing that lives under bridges
  and munches goats, the O sound is shorter, and more 
  towards the back of my mouth.
 
 Native English accents vary as well, but _roll_ rhymes with _troll_, not 
 _trawl_.  _Trawl_ would rhyme with _fall_, and _fall_ definitely doesn't 
 rhyme with _roll_.
 

I did not mean using a net to scour the seabed - Trawl,
I meant using a spoon to see what you can induce to strike - Troll

- Hendrik

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-01 Thread Steve Holden
Dennis Lee Bieber wrote:
 On Fri, 31 Aug 2007 21:15:10 +0100, DaveM [EMAIL PROTECTED]
 declaimed the following in comp.lang.python:
 
 
 No - but I would pronounce lever and fever the same way, if that helps.

   shudder To me, those are different... I suppose you also add an
 extra i to aluminum G

No, he just spells it with two i's like sensible people do. Who would 
ever want *three* I's in aluminium (which, by the way, you misspelled ;-)?

Such things are matters of practical significance to me, since I have 
adopted a policy of using English spelling when in the UK and US 
spelling when elsewhere. Since I am now pretty much full-time in the US, 
I am finally having to come to terms with its crazy spelling.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-01 Thread Hendrik van Rooyen
Paddy pado.mail.com wrote:
 
 I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll
 and role similarly.
 
 My accent is probably from the East Midlands of the UK, but is not
 pronounced.

Same here - when the Troll lives under a bridge - I could not think
of something to rhyme with it - frolic is just right.

- Hendrik

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index() (OT)

2007-09-01 Thread Hendrik van Rooyen
Richie Hindle richi...ian.com wrote:

 But - the word for someone who posts to the internet with the intention of
 stirring up trouble derives from the word for what fishermen do, not from
 the word for something that lives under a bridge.  It derives from trolling
 for suckers or trolling for newbies.

So am I right in asserting that there is a difference in pronunciation
of the noun and the verb?

He is a Troll - like the excellent frolic example
He likes to Troll - rhymes with roll?

- Hendrik

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index() (OT)

2007-09-01 Thread Steve Holden
Hendrik van Rooyen wrote:
 Richie Hindle richi...ian.com wrote:
 
 But - the word for someone who posts to the internet with the intention of
 stirring up trouble derives from the word for what fishermen do, not from
 the word for something that lives under a bridge.  It derives from trolling
 for suckers or trolling for newbies.
 
 So am I right in asserting that there is a difference in pronunciation
 of the noun and the verb?
 
 He is a Troll - like the excellent frolic example
 He likes to Troll - rhymes with roll?
 
I think you are seeking consistency where none exists. I don't believe 
anyone uses different pronunciations for the noun and the verb (which I 
guess will make those who *do* come out of the woodwork in double-quick 
time).

Where's Godwin's Law when yo need it?

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-01 Thread Ben Finney
Dennis Lee Bieber [EMAIL PROTECTED] writes:

 I suppose you also add an extra i to aluminum G

We're not out to rewrite the table of elements. There's no such thing
as aluminum, and aluminium always has just the two is.

-- 
 \  Rightful liberty is unobstructed action, according to our |
  `\will, within limits drawn around us by the equal rights of |
_o__)others.  -- Thomas Jefferson |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index() (OT)

2007-09-01 Thread Paddy
On Sep 1, 7:57 am, Hendrik van Rooyen [EMAIL PROTECTED] wrote:
 Richie Hindle richi...ian.com wrote:
  But - the word for someone who posts to the internet with the intention of
  stirring up trouble derives from the word for what fishermen do, not from
  the word for something that lives under a bridge.  It derives from trolling
  for suckers or trolling for newbies.

 So am I right in asserting that there is a difference in pronunciation
 of the noun and the verb?

 He is a Troll - like the excellent frolic example
 He likes to Troll - rhymes with roll?

 - Hendrik

No difference. A troll is a troll is a troll.

:-)

- Paddy.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index() (OT) and definitely trolling :-)

2007-09-01 Thread Paddy
On Sep 1, 7:32 am, Steve Holden [EMAIL PROTECTED] wrote:
 Dennis Lee Bieber wrote:
  On Fri, 31 Aug 2007 21:15:10 +0100, DaveM [EMAIL PROTECTED]
  declaimed the following in comp.lang.python:

  No - but I would pronounce lever and fever the same way, if that helps.

 shudder To me, those are different... I suppose you also add an
  extra i to aluminum G

 No, he just spells it with two i's like sensible people do. Who would
 ever want *three* I's in aluminium (which, by the way, you misspelled ;-)?

 Such things are matters of practical significance to me, since I have
 adopted a policy of using English spelling when in the UK and US
 spelling when elsewhere. Since I am now pretty much full-time in the US,
 I am finally having to come to terms with its crazy spelling.

 regards
   Steve
 --
 Steve Holden+1 571 484 6266   +1 800 494 3119
 Holden Web LLC/Ltd  http://www.holdenweb.com
 Skype: holdenweb  http://del.icio.us/steve.holden
 --- Asciimercial --
 Get on the web: Blog, lens and tag the Internet
 Many services currently offer free registration
 --- Thank You for Reading -

Since the language that inspired the programming language is most
definitely English as spoken in the UK, could it be that the highest
levels of Pythonistic Nirvana are to be reached only by 
Nah - can't do it! (just spell colour right and I'll be OK).

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-01 Thread Steven D'Aprano
On Sat, 01 Sep 2007 17:23:04 +1000, Ben Finney wrote:

 Dennis Lee Bieber [EMAIL PROTECTED] writes:
 
 I suppose you also add an extra i to aluminum G
 
 We're not out to rewrite the table of elements. There's no such thing as
 aluminum, and aluminium always has just the two is.

Although aluminium is the one and only correct spelling *grins*, it is 
not actually true that it has always been spelt that way (or for you 
Merkins out there, spelled). The discoverer of aluminium, Sir Humphrey 
Davy, originally spelt it alumium, then aluminum, and finally 
standardized on aluminium.

http://www.worldwidewords.org/articles/aluminium.htm


-- 
Steven.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-01 Thread Hendrik van Rooyen
 Steve Holden [EMAIL PROTECTED] wrote:


 Paddy wrote:
  My accent is probably from the East Midlands of the UK, but is not
  pronounced.
  
 If your accent isn't pronounced how do we know what it sounds like?
 

When he says pronounced, he doesn't mean pronounced,  he means pronounced!

-  To shamelessly paraphrase the Master - (Plum of course)

; - )  - Hendrik

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index() (OT)

2007-09-01 Thread Hendrik van Rooyen
 Steve Holden s...web.com wrote:


 Where's Godwin's Law when yo need it?

Hitler would not have spellt you like that...

- Hendrik

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index() (OT)

2007-09-01 Thread Ricardo Aráoz
Paddy wrote:
 On Sep 1, 7:57 am, Hendrik van Rooyen [EMAIL PROTECTED] wrote:
 Richie Hindle richi...ian.com wrote:
 But - the word for someone who posts to the internet with the intention of
 stirring up trouble derives from the word for what fishermen do, not from
 the word for something that lives under a bridge.  It derives from trolling
 for suckers or trolling for newbies.
 So am I right in asserting that there is a difference in pronunciation
 of the noun and the verb?

 He is a Troll - like the excellent frolic example
 He likes to Troll - rhymes with roll?

 - Hendrik
 
 No difference. A troll is a troll is a troll.
 
 :-)
 
 - Paddy.


BTW people , the word for what fishermen do is  T R A W L  and not troll
(Ha! and I'm not a native English speaker).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index() (OT)

2007-09-01 Thread Steve Holden
Ricardo Aráoz wrote:
 Paddy wrote:
 On Sep 1, 7:57 am, Hendrik van Rooyen [EMAIL PROTECTED] wrote:
 Richie Hindle richi...ian.com wrote:
 But - the word for someone who posts to the internet with the intention of
 stirring up trouble derives from the word for what fishermen do, not from
 the word for something that lives under a bridge.  It derives from 
 trolling
 for suckers or trolling for newbies.
 So am I right in asserting that there is a difference in pronunciation
 of the noun and the verb?

 He is a Troll - like the excellent frolic example
 He likes to Troll - rhymes with roll?

 - Hendrik
 No difference. A troll is a troll is a troll.

 :-)

 - Paddy.
 
 
 BTW people , the word for what fishermen do is  T R A W L  and not troll
 (Ha! and I'm not a native English speaker).

Just read the whole thread, or use a dictionary: in fishing, trolling 
and trawling are two different things; the first is done with a net, the 
second with a line.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index() (OT)

2007-09-01 Thread Ricardo Aráoz
Steve Holden wrote:
 Ricardo Aráoz wrote:
 Paddy wrote:
 On Sep 1, 7:57 am, Hendrik van Rooyen [EMAIL PROTECTED] wrote:
 Richie Hindle richi...ian.com wrote:
 But - the word for someone who posts to the internet with the intention of
 stirring up trouble derives from the word for what fishermen do, not from
 the word for something that lives under a bridge.  It derives from 
 trolling
 for suckers or trolling for newbies.
 So am I right in asserting that there is a difference in pronunciation
 of the noun and the verb?

 He is a Troll - like the excellent frolic example
 He likes to Troll - rhymes with roll?

 - Hendrik
 No difference. A troll is a troll is a troll.

 :-)

 - Paddy.

 BTW people , the word for what fishermen do is  T R A W L  and not troll
 (Ha! and I'm not a native English speaker).
 
 Just read the whole thread, or use a dictionary: in fishing, trolling 
 and trawling are two different things; the first is done with a net, the 
 second with a line.
 
 regards
   Steve

Damn Wikipedia! It always gets things upside down, specially when I
'read the whole thread' :

Trolling for fish is a form of angling where lines with hook-rigged
lures are dragged behind a boat to entice fish to bite. Compare the term
Trawling for fish, which involves dragging a net behind a boat to
catch large numbers of fish.

;c)

(Don't mind me. Just trolling...)




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-01 Thread Nicko
On Aug 30, 7:00 pm, Steve Holden [EMAIL PROTECTED] wrote:

 You can also generate the files that are in one directory but ot the
 other with

 (afiles | bfiles) - (afiles  bfiles)

Or just (afiles ^ bfiles).

Nicko

--
(lambda f: lambda *a:f(f,*a))(
lambda f,l,i:l[i][1]+f(f,l,l[i][0]) if l[i][0]0 else )(
sorted(enumerate('[EMAIL PROTECTED]'),key=lambda a:a[1]),0)[1:]

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-01 Thread Michael L Torrie
[EMAIL PROTECTED] wrote:
 In my case of have done os.listdir() on two directories. I want to see
 what files are in directory A that are not in directory B.
 I have used exceptions in other languages and only do so on logic that
 should never happen. In this case it is known that some of the files
 will not be in both lists. I just want to know which ones.
 

What's wrong, then, with doing:

if i in list:
   print list.index(i)

Since if, as you proposed, list.index() returned some value to represent
 not found, you'd require an if anyway.

This is probably not pythonic, but at least it would overcome your
exceptions excuse.

If we were to program this .index() method in some language that
enforces contracts, like haskell, then we'd say that .index() expects a
value that exists in the list.  So if you violate the contract, why
should you expect to *not* get an exception.  Doing it any other way,
though, makes the code a lot more error prone.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-01 Thread Michael L Torrie
Alex Martelli wrote:

 is the one obvious way to do it (the set(...) is just a simple and
 powerful optimization -- checking membership in a set is roughly O(1),
 while checking membership in a list of N items is O(N)...).

Depending on a how a set is stored, I'd estimate any membership check in
a set to be O(log N).  That's if it's stored in a tree of some kind,
which you'd need to fast finding.  Say a balanced binary tree.  Worst
case, you'd have to search half of the elements to find what you were
looking for.

 
 
 Alex

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-01 Thread Marc 'BlackJack' Rintsch
On Sat, 01 Sep 2007 13:44:28 -0600, Michael L Torrie wrote:

 Alex Martelli wrote:
 
 is the one obvious way to do it (the set(...) is just a simple and
 powerful optimization -- checking membership in a set is roughly O(1),
 while checking membership in a list of N items is O(N)...).
 
 Depending on a how a set is stored, I'd estimate any membership check in
 a set to be O(log N).

Sets are stored as hash tables so membership check is O(1) just like Alex
said.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-01 Thread Marc 'BlackJack' Rintsch
On Sat, 01 Sep 2007 13:37:29 -0600, Michael L Torrie wrote:

 What's wrong, then, with doing:
 
 if i in list:
print list.index(i)

If `i` is in the list this does the linear lookup twice.

 If we were to program this .index() method in some language that
 enforces contracts, like haskell, then we'd say that .index() expects a
 value that exists in the list.  So if you violate the contract, why
 should you expect to *not* get an exception.  Doing it any other way,
 though, makes the code a lot more error prone.

Does Haskell exceptions?  In Haskell I would expect such a function to
return the `Maybe` type.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-09-01 Thread Alex Martelli
Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:

 On Sat, 01 Sep 2007 13:44:28 -0600, Michael L Torrie wrote:
 
  Alex Martelli wrote:
  
  is the one obvious way to do it (the set(...) is just a simple and
  powerful optimization -- checking membership in a set is roughly O(1),
  while checking membership in a list of N items is O(N)...).
  
  Depending on a how a set is stored, I'd estimate any membership check in
  a set to be O(log N).
 
 Sets are stored as hash tables so membership check is O(1) just like Alex
 said.

Roughly O(1), as I said, because of the usual issues with cost of
hashing, potential hashing conflicts, re-hashing (which requires
thinking in terms of *amortized* big-O, just like, say, list appends!),
etc, just like for any hash table implementation (though Python's, long
used and finely tuned in dicts then adopted for sets, is an exceedingly
good implementation, it IS possible to artificially construct a worst
case -- e.g., set(23+sys.maxint*i*2+i for i in xrange(24,199))...)


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread Terry Reedy

Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
| On Thu, 30 Aug 2007 17:09:36 +1000, Ben Finney wrote:
|
|  [EMAIL PROTECTED] writes:
| 
|  What's with the index() function of lists throwing an exception on not
|  found?
| 
|  It's letting you know that the item isn't in the list. There's no
|  sensible return value from an index function in that condition.
|
| What about -1?  C programmers do this all the time.  :-)

Because they do not have exceptions. 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
 On Aug 30, 4:28 pm, Ben Finney [EMAIL PROTECTED]
 wrote:
 [EMAIL PROTECTED] writes:
 On Aug 30, 12:09 am, Ben Finney [EMAIL PROTECTED]
 wrote:
 It's letting you know that the item isn't in the list. There's no
 sensible return value from an index function in that condition.
 for str:
 find(  sub[, start[, end]])
 [...]
 Return -1 if sub is not found.
 -1 is used in other languages as well.
 It is no more sensible there than in the 'str.find' method, which is a
 historical wart.
 
 One man's sensible is another man's insensible. For instance, some
 people feel -1 as a valid index into a list is sensible. Other's find
 it insensible.

Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type help, copyright, credits or license for more information.
  print sensible[-1]
e
 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread Hendrik van Rooyen
Carsten Haese car...ys.com wrote:

 .. If we start labeling
 people, this thread will earn you a label that rhymes with roll.

weird this - maybe a native English speaker can comment - 
when I pronounce what fishermen do - it rhymes with roll,
but when I am talking about the thing that lives under bridges
and munches goats, the O sound is shorter, and more 
towards the back of my mouth.

- Hendrik

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread Erik Max Francis
Hendrik van Rooyen wrote:

 weird this - maybe a native English speaker can comment - 
 when I pronounce what fishermen do - it rhymes with roll,
 but when I am talking about the thing that lives under bridges
 and munches goats, the O sound is shorter, and more 
 towards the back of my mouth.

Native English accents vary as well, but _roll_ rhymes with _troll_, not 
_trawl_.  _Trawl_ would rhyme with _fall_, and _fall_ definitely doesn't 
rhyme with _roll_.

-- 
Erik Max Francis  [EMAIL PROTECTED]  http://www.alcyone.com/max/
  San Jose, CA, USA  37 20 N 121 53 W  AIM, Y!M erikmaxfrancis
   I do not like work even when someone else does it.
-- Mark Twain
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
(snip)
 I don't think that is the definition used across computer science.
 
 It suddenly dawned on me that what would be best would be a contains()
 (or IN syntax for those who can't afford to wait) for lists.

No need to wait:

  'a' in ['a', 'b']
True
  ['a', 'b'].__contains__('a')
True


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread Paddy
On Aug 31, 8:47 am, Erik Max Francis [EMAIL PROTECTED] wrote:
 Hendrik van Rooyen wrote:
  weird this - maybe a native English speaker can comment -
  when I pronounce what fishermen do - it rhymes with roll,
  but when I am talking about the thing that lives under bridges
  and munches goats, the O sound is shorter, and more
  towards the back of my mouth.

 Native English accents vary as well, but _roll_ rhymes with _troll_, not
 _trawl_.  _Trawl_ would rhyme with _fall_, and _fall_ definitely doesn't
 rhyme with _roll_.

 --
 Erik Max Francis  [EMAIL PROTECTED] http://www.alcyone.com/max/
   San Jose, CA, USA  37 20 N 121 53 W  AIM, Y!M erikmaxfrancis
I do not like work even when someone else does it.
 -- Mark Twain

I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll
and role similarly.

My accent is probably from the East Midlands of the UK, but is not
pronounced.

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread Erik Max Francis
Paddy wrote:

 I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll
 and role similarly.

 My accent is probably from the East Midlands of the UK, but is not
 pronounced.

_Troll_ and _frolic_ aren't pronounced with the same o sound in any 
accent I've ever heard of.  Which you pronounce _boat_ and _bot_ the 
same way, too?

-- 
Erik Max Francis  [EMAIL PROTECTED]  http://www.alcyone.com/max/
  San Jose, CA, USA  37 20 N 121 53 W  AIM, Y!M erikmaxfrancis
   There are no dull subjects. There are only dull writers.
-- H.L. Mencken
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread Tim Golden
Erik Max Francis wrote:
 Paddy wrote:
 
 I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll
 and role similarly.

 My accent is probably from the East Midlands of the UK, but is not
 pronounced.
 
 _Troll_ and _frolic_ aren't pronounced with the same o sound in any 
 accent I've ever heard of.  Which you pronounce _boat_ and _bot_ the 
 same way, too?

[Amusingly contemplating a trolling war about the pronunciation of troll]

Well they sound the same in my more-or-less South London accent.
I can't write those funny phonetic symbols (and I hate to
imagine the Unicode encoding hoops I'd have to jump through
to make them readable anyway) but both os sound short to me.
Like bot rather than boat using your example.

TJG
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread Jon Ribbens
On 2007-08-31, Erik Max Francis [EMAIL PROTECTED] wrote:
 I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll
 and role similarly.

 My accent is probably from the East Midlands of the UK, but is not
 pronounced.

 _Troll_ and _frolic_ aren't pronounced with the same o sound in any 
 accent I've ever heard of.

Welcome to England!

 Which you pronounce _boat_ and _bot_ the same way, too?

No. HTH HAND.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread Richie Hindle

[Carsten]
 .. If we start labeling
 people, this thread will earn you a label that rhymes with roll.

[Hendrik]
 weird this - maybe a native English speaker can comment - 
 when I pronounce what fishermen do - it rhymes with roll,
 but when I am talking about the thing that lives under bridges
 and munches goats, the O sound is shorter, and more 
 towards the back of my mouth.

But - the word for someone who posts to the internet with the intention of
stirring up trouble derives from the word for what fishermen do, not from
the word for something that lives under a bridge.  It derives from trolling
for suckers or trolling for newbies.

-- 
Richie Hindle
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread Carsten Haese
On Thu, 30 Aug 2007 21:33:43 -0700, TheFlyingDutchman wrote
 On Aug 30, 9:06 pm, Carsten Haese [EMAIL PROTECTED] wrote:
  On Thu, 30 Aug 2007 20:17:00 -0700, zzbbaadd wrote
 
   Well IN was what I was looking for and would have saved this thread.
   However I don't believe IN showed up on the doc web page that has
   list methods, where I found index().
 
  They're not on the exact same page, but index() is in section 3.6.4 of the
  library reference (http://docs.python.org/lib/typesseq-mutable.html), 
  whereas
  in is in section 3.6 of the library reference
  (http://docs.python.org/lib/typesseq.html). I'm wondering how you managed to
  find subsection 3.6.4 without finding section 3.6.
 
 www.google.com
 
 search python list methods
 
 first search find:
 
 5. Data Structures
 The list methods make it very easy to use a list as a stack, where 
 the last element added  Another useful data type built into 
 Python is the dictionary. ... http://docs.python.org/tut/node7.html
 
 The list data type has some more methods. Here are all of the 
 methods of list objects:

Fair enough, but that's a tutorial. It would be foolish to demand that a
tutorial be a complete reference for everything that can be done with a list.
The page lists all methods of list objects, but there are more things one can
do with lists that don't look like method calls. For example, it doesn't say
that you can compare lists. It doesn't say that you can read and write
elements in the lists. Would you automatically assume that those things aren't
possible? I hope not. (Of course, those operations are handled by the magical
methods __eq__, __setitem__, __getitem__ etc, but I think one can forgive the
tutorial for not mentioning those in the interest of not confusing beginners.)

By your logic, no web page would be allowed to say anything about lists unless
it says *everything* about lists, and that wouldn't be very useful.

--
Carsten Haese
http://informixdb.sourceforge.net

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread TheFlyingDutchman


 Fair enough, but that's a tutorial. It would be foolish to demand that a
 tutorial be a complete reference for everything that can be done with a list.

I wasn't demanding anything of the page. I was pointing out how I made
the assumption there was no way to find out if a list has a value
other than by using index(). I am not used to having keywords in a
language operate on a data structure, in addition to its methods.

 The page lists all methods of list objects, but there are more things one can
 do with lists that don't look like method calls. For example, it doesn't say
 that you can compare lists. It doesn't say that you can read and write
 elements in the lists. Would you automatically assume that those things aren't
 possible? I hope not. (Of course, those operations are handled by the magical
 methods __eq__, __setitem__, __getitem__ etc, but I think one can forgive the
 tutorial for not mentioning those in the interest of not confusing beginners.)

 By your logic, no web page would be allowed to say anything about lists unless
 it says *everything* about lists, and that wouldn't be very useful.

As I just stated, I wasn't making a criticism of the page. But since
you are defending it, let's talk about Python documentation from the
perspective of an experienced programmer who is a new/casual user of
both Python and Java. If I am in the process of writing a little Java
program, java.sun.com provides documentation on its data structures
that show up right at the top of a google search for Java ArrayList,
Java Hashtable, etc.

If I am writing a little Python program and want to see what I can do
with a list, I google python list I get the tutorial page that has
been mentioned. Then the next query result is a page that is titled
the Python Language Reference. But in this reference page for
python str,unicode,list,tuple,buffer,xrange, I see operators that
work on lists and other data structures that I an mot concerned with,
but there is no list of list methods. But I do see navigational
arrows that I hopefully assume will take me to a page where I can find
all the list methods - but that is not the case. I go from 3.6
Sequence Types -- str, unicode, list, tuple, buffer, xrange to 3.6.1
String Methods to 3.6.2 String Formatting Operations to 3.6.3
XRange Type to 3.6.4 Mutable Sequence Types. And then I'm done with
3.6 of the Python Language Reference and I never saw a list of list
methods or a page devoted to lists. So I bounce out to the table of
contents assuming that there must be an entry for list that will
show all the list methods and operators and give me a summary ala Java
ArrayList. But all I find are entries for UserList and AddressList. :(

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread BJörn Lindqvist
On 8/30/07, Carsten Haese [EMAIL PROTECTED] wrote:
 Is the Pythonic way

 try:
 i = somelist.index(thing)
 # Do something with i
 except IndexError:
 # Do something if thing not found

That is not the Pythonic way. # Do something with i might also raise
an IndexError and they you are screwed. The Pythonic way is something
like:

try:
i = somelist.index(thing)
except IndexError:
print Oh noes!
else:
# Do the thing with i

And for many cases this actually is worse/less readable than the
alternative would have been if list.index() returned -1.


-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread Alex Martelli
[EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
   ...
 Why wouldn't the one obvious way be:
 
  def inAnotB(A, B):
  inA  = set(os.listdir(A))
  inBs = set(os.listdir(B))
  return inA.difference(inBs)

If you want a set as the result, that's one possibility (although
possibly a bit wasteful as you're building one more set than necessary);
I read the original request as implying a sorted list result is wanted,
just like os.listdir returns (possibly sorted in case-independent order
depending on the underlying filesystem).  There's no real added value in
destroying inA's ordering by making it a set, when the list
comprehension just naturally keeps its ordering.


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread MRAB
On Aug 31, 11:05 am, Jon Ribbens [EMAIL PROTECTED] wrote:
 On 2007-08-31, Erik Max Francis [EMAIL PROTECTED] wrote:

  I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll
  and role similarly.

  My accent is probably from the East Midlands of the UK, but is not
  pronounced.

  _Troll_ and _frolic_ aren't pronounced with the same o sound in any
  accent I've ever heard of.

 Welcome to England!

  Which you pronounce _boat_ and _bot_ the same way, too?

 No. HTH HAND.

For some, troll rhymes with roll, for others, with doll. Does it
matter?

As for the pronunciation of Python, let's ask Guido! :-)

-- 
http://mail.python.org/mailman/listinfo/python-list


troll vs. trawl [was: Re: list index()]

2007-08-31 Thread David Naughton
On Fri, Aug 31, 2007 at 10:27:34AM +0100, Richie Hindle wrote:
 
 [Carsten]
  .. If we start labeling
  people, this thread will earn you a label that rhymes with roll.
 
 [Hendrik]
  weird this - maybe a native English speaker can comment - 
  when I pronounce what fishermen do - it rhymes with roll,
  but when I am talking about the thing that lives under bridges
  and munches goats, the O sound is shorter, and more 
  towards the back of my mouth.
 
 But - the word for someone who posts to the internet with the intention of
 stirring up trouble derives from the word for what fishermen do, not from
 the word for something that lives under a bridge.  It derives from trolling
 for suckers or trolling for newbies.

Many thesauri list the 'troll' as a synonym of 'trawl'. Given their
etymologies...

1. 'trawl' is 'probably from L. tragula dragnet.'
  -- URL: http://www.etymonline.com/index.php?term=trawl

2. blockquote

troll (v.) 
1377, to go about, stroll, later (c.1425) roll from side to side,
trundle, from O.Fr. troller, a hunting term, wander, to go in quest of
game without purpose, from a Gmc. source (cf. O.H.G. trollen to walk
with short steps), from P.Gmc. *truzlanan. Sense of sing in a full,
rolling voice (first attested 1575) and that of fish with a moving
line (1606) are both extended technical applications of the general
sense of roll, trundle, the latter perhaps confused with trail or
trawl. Fig. sense of to draw on as with a moving bait, entice, allure
is from 1565. Meaning to cruise in search of sexual encounters is
recorded from 1967, originally in homosexual slang.

/blockquote

  -- URL: http://www.etymonline.com/index.php?term=troll

... it was probably inevitable that 'troll' and 'trawl' become
synonymous.

David
 
 -- 
 Richie Hindle
 [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread Steve Holden
Paddy wrote:
 On Aug 31, 8:47 am, Erik Max Francis [EMAIL PROTECTED] wrote:
 Hendrik van Rooyen wrote:
 weird this - maybe a native English speaker can comment -
 when I pronounce what fishermen do - it rhymes with roll,
 but when I am talking about the thing that lives under bridges
 and munches goats, the O sound is shorter, and more
 towards the back of my mouth.
 Native English accents vary as well, but _roll_ rhymes with _troll_, not
 _trawl_.  _Trawl_ would rhyme with _fall_, and _fall_ definitely doesn't
 rhyme with _roll_.

 --
 Erik Max Francis  [EMAIL PROTECTED] http://www.alcyone.com/max/
   San Jose, CA, USA  37 20 N 121 53 W  AIM, Y!M erikmaxfrancis
I do not like work even when someone else does it.
 -- Mark Twain
 
 I say the 'oll' in troll like the 'ol' in frolic, and pronounce roll
 and role similarly.
 
 My accent is probably from the East Midlands of the UK, but is not
 pronounced.
 
If your accent isn't pronounced how do we know what it sounds like?

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread Steve Holden
Alex Martelli wrote:
 [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
...
 Why wouldn't the one obvious way be:

  def inAnotB(A, B):
  inA  = set(os.listdir(A))
  inBs = set(os.listdir(B))
  return inA.difference(inBs)
 
 If you want a set as the result, that's one possibility (although
 possibly a bit wasteful as you're building one more set than necessary);
 I read the original request as implying a sorted list result is wanted,
 just like os.listdir returns (possibly sorted in case-independent order
 depending on the underlying filesystem).  There's no real added value in
 destroying inA's ordering by making it a set, when the list
 comprehension just naturally keeps its ordering.
 
As I had reason to point out in another thread only recently, 
os.listdir() makes no promises about the filename ordering.

Nevertheless I agree with you that the list comprehension method is the 
obvious way to solve the problem, and the set optimization is just that.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread DaveM
On Fri, 31 Aug 2007 02:37:15 -0700, Erik Max Francis [EMAIL PROTECTED]
wrote:

_Troll_ and _frolic_ aren't pronounced with the same o sound in any 
accent I've ever heard of.  

You've never heard an English accent then.

Which you pronounce _boat_ and _bot_ the same way, too?

No - but I would pronounce lever and fever the same way, if that helps.

DaveM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread Lawrence D'Oliveiro
In message [EMAIL PROTECTED], Carsten
Haese wrote:

 On Thu, 2007-08-30 at 11:21 -0700, [EMAIL PROTECTED] wrote:

 I wish they were not
 getting rid of dict.has_key() in Python 3, which I prefer to IN.
 
 That wish will only come true if you maintain your own fork of Python 3.
 has_key() will go away, period. It has been made obsolete by in, which
 is faster and more concise.

And is also a backdoor way of introducing non-virtual methods into Python,
is it not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-31 Thread Carsten Haese
On Sat, 2007-09-01 at 13:50 +1200, Lawrence D'Oliveiro wrote:
 In message [EMAIL PROTECTED], Carsten
 Haese wrote:
  has_key() will go away, period. It has been made obsolete by in, which
  is faster and more concise.
 
 And is also a backdoor way of introducing non-virtual methods into Python,
 is it not.

If by that you mean that in tests can't be overridden, that's not
true:

 class LyingDict(dict):
...   def __contains__(self, key): return False
... 
 d = LyingDict()
 d[1] = 42
 1 in d
False

If you mean something else, please clarify.

-- 
Carsten Haese
http://informixdb.sourceforge.net


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Marc 'BlackJack' Rintsch
On Wed, 29 Aug 2007 23:44:33 -0700, zzbbaadd wrote:

 What's with the index() function of lists throwing an exception on not
 found? Let's hope this is rectified in Python 3. If nothing else, add
 a function that doesn't throw an exception. There are a million
 situations where you can have an item not be in a list and it is not
 an exception situation.

Write such a function yourself, it is quite easy after all.  I very seldom
use the `list.index()` method.  What do your millions situations look like?
Maybe there is a better data structure than lists for those situations!?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Ben Finney
[EMAIL PROTECTED] writes:

 What's with the index() function of lists throwing an exception on not
 found?

It's letting you know that the item isn't in the list. There's no
sensible return value from an index function in that condition.

 Let's hope this is rectified in Python 3. If nothing else, add a
 function that doesn't throw an exception.

You can easily create one:

def get_an_index_even_if_not_found(the_list, the_item):
bogus_index_value = object()
try:
index = the_list.index(the_value)
except ValueError:
index = bogus_index_value
return index

It's up to you to figure out what bogus_index_value you want to
use. The rest of us will continue to catch the exception where needed.

-- 
 \  Reichel's Law: A body on vacation tends to remain on vacation |
  `\ unless acted upon by an outside force.  -- Carol Reichel |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Marc 'BlackJack' Rintsch
On Thu, 30 Aug 2007 17:09:36 +1000, Ben Finney wrote:

 [EMAIL PROTECTED] writes:
 
 What's with the index() function of lists throwing an exception on not
 found?
 
 It's letting you know that the item isn't in the list. There's no
 sensible return value from an index function in that condition.

What about -1?  C programmers do this all the time.  :-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
 What's with the index() function of lists throwing an exception on not
 found? Let's hope this is rectified in Python 3. If nothing else, add
 a function that doesn't throw an exception. There are a million
 situations where you can have an item not be in a list and it is not
 an exception situation.

What's with using your brain instead of whining ?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Ben Finney
Marc 'BlackJack' Rintsch [EMAIL PROTECTED] writes:

 On Thu, 30 Aug 2007 17:09:36 +1000, Ben Finney wrote:
  It's letting you know that the item isn't in the list. There's no
  sensible return value from an index function in that condition.
 
 What about -1?  C programmers do this all the time.  :-)

I don't believe you've contradicted me :-)

-- 
 \If you ever drop your keys into a river of molten lava, let |
  `\  'em go, because, man, they're gone.  -- Jack Handey |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Ben Finney
Bruno Desthuilliers [EMAIL PROTECTED] writes:

 What's with using your brain instead of whining ?

Now now, no need for snappiness. If you don't feel a constructive
response is merited, please ignore.

-- 
 \   A lot of people are afraid of heights. Not me, I'm afraid of |
  `\widths.  -- Steven Wright |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Ben Finney
Ben Finney [EMAIL PROTECTED] writes:

 def get_an_index_even_if_not_found(the_list, the_item):

Bah. Should be …(the_list, the_value):.

-- 
 \Don't worry about people stealing your ideas. If your ideas |
  `\are any good, you'll have to ram them down people's throats.  |
_o__)  -- Howard Aiken |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: list index()

2007-08-30 Thread Bruno Desthuilliers
Ben Finney a écrit :
 Bruno Desthuilliers [EMAIL PROTECTED] writes:
 
 What's with using your brain instead of whining ?
 
 Now now, no need for snappiness. If you don't feel a constructive
 response is merited, please ignore.

Yes, you're right. Sorry.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Carsten Haese
On Wed, 2007-08-29 at 23:44 -0700, [EMAIL PROTECTED] wrote:
 What's with the index() function of lists throwing an exception on not
 found? Let's hope this is rectified in Python 3.

You're assuming that this behavior is a mistake. It's not, and
consequently, it won't be rectified.

  If nothing else, add
 a function that doesn't throw an exception. There are a million
 situations where you can have an item not be in a list and it is not
 an exception situation.

How could it not be an exception, in the plain English sense of the
word? Most certainly you're asking for the index because you want to do
something with the index. If the item is not found, you have no index,
so that's a special case that must be handled separately. There is no
logical difference between handling that special case in an except
clause versus handling it with an if-branch.

Is the Pythonic way

try:
i = somelist.index(thing)
# Do something with i
except IndexError:
# Do something if thing not found

really that much worse than the theoretical alternative

i = somelist.index_that_returns_an_indicator(thing)
if i!=ThingNotFoundIndicator:
# Do something with i
else:
# Do something if thing not found

?

-- 
Carsten Haese
http://informixdb.sourceforge.net


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Marshall T. Vandegrift
[EMAIL PROTECTED] writes:

 What's with the index() function of lists throwing an exception on not
 found? Let's hope this is rectified in Python 3. If nothing else, add
 a function that doesn't throw an exception. There are a million
 situations where you can have an item not be in a list and it is not
 an exception situation.

The Python string types have both the method `index()` which throws an
exception and the method `find()` which implements the same behavior but
returns -1 for not-found substrings.  I would naively have assumed the
`list` type to provide both as well, but it provides only `index()`.

Anyone know the reason for this lack of parallelism?

-Marshall

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Marc 'BlackJack' Rintsch
On Thu, 30 Aug 2007 09:53:53 -0400, Marshall T. Vandegrift wrote:

 The Python string types have both the method `index()` which throws an
 exception and the method `find()` which implements the same behavior but
 returns -1 for not-found substrings.  I would naively have assumed the
 `list` type to provide both as well, but it provides only `index()`.
 
 Anyone know the reason for this lack of parallelism?

Historical reasons and IIRC the `find()` method on strings will go away in
Python 3.0.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: list index()

2007-08-30 Thread zzbbaadd
On Aug 30, 12:09 am, Ben Finney [EMAIL PROTECTED]
wrote:
 [EMAIL PROTECTED] writes:
  What's with the index() function of lists throwing an exception on not
  found?

 It's letting you know that the item isn't in the list. There's no
 sensible return value from an index function in that condition.

for str:

find(   sub[, start[, end]])
Return the lowest index in the string where substring sub is
found, such that sub is contained in the range [start, end]. Optional
arguments start and end are interpreted as in slice notation. Return
-1 if sub is not found.

-1 is used in other languages as well.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread zzbbaadd

 How could it not be an exception, in the plain English sense of the
 word? Most certainly you're asking for the index because you want to do
 something with the index. If the item is not found, you have no index,
 so that's a special case that must be handled separately. There is no
 logical difference between handling that special case in an except
 clause versus handling it with an if-branch.

In my case of have done os.listdir() on two directories. I want to see
what files are in directory A that are not in directory B.
I have used exceptions in other languages and only do so on logic that
should never happen. In this case it is known that some of the files
will not be in both lists. I just want to know which ones.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Robert Kern
[EMAIL PROTECTED] wrote:
 How could it not be an exception, in the plain English sense of the
 word? Most certainly you're asking for the index because you want to do
 something with the index. If the item is not found, you have no index,
 so that's a special case that must be handled separately. There is no
 logical difference between handling that special case in an except
 clause versus handling it with an if-branch.
 
 In my case of have done os.listdir() on two directories. I want to see
 what files are in directory A that are not in directory B.
 I have used exceptions in other languages and only do so on logic that
 should never happen.

Python is different than those languages. Exceptions are used much more
frequently in Python and often for things that will *definitely* happen not just
those things that shouldn't.

-- 
Robert Kern

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread zzbbaadd
On Aug 30, 12:42 am, Bruno Desthuilliers bruno.
[EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] a écrit :


 What's with using your brain instead of whining ?

I knew there would be at least one religious zealot.


-- 
http://mail.python.org/mailman/listinfo/python-list

Re: list index()

2007-08-30 Thread Steve Holden
[EMAIL PROTECTED] wrote:
 How could it not be an exception, in the plain English sense of the
 word? Most certainly you're asking for the index because you want to do
 something with the index. If the item is not found, you have no index,
 so that's a special case that must be handled separately. There is no
 logical difference between handling that special case in an except
 clause versus handling it with an if-branch.
 
 In my case of have done os.listdir() on two directories. I want to see
 what files are in directory A that are not in directory B.
 I have used exceptions in other languages and only do so on logic that
 should never happen. In this case it is known that some of the files
 will not be in both lists. I just want to know which ones.
 
And, as is so often the case, once the *real* problem is stated a more 
elegant solution become available - in this case, using sets.

afiles = set(os.listdir(dira))
bfiles = set(os.listdir(dirb))

for f in (afiles - bfiles):
   print Not common:, f


You can also generate the files that are in one directory but ot the 
other with

(afiles | bfiles) - (afiles  bfiles)

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Carsten Haese
On Thu, 2007-08-30 at 10:44 -0700, [EMAIL PROTECTED] wrote:
 
  How could it not be an exception, in the plain English sense of the
  word? Most certainly you're asking for the index because you want to do
  something with the index. If the item is not found, you have no index,
  so that's a special case that must be handled separately. There is no
  logical difference between handling that special case in an except
  clause versus handling it with an if-branch.
 
 In my case of have done os.listdir() on two directories. I want to see
 what files are in directory A that are not in directory B.
 [...]

list.index() is the wrong tool for that job. Python has sets, use them.

-- 
Carsten Haese
http://informixdb.sourceforge.net


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Carsten Haese
On Thu, 2007-08-30 at 10:56 -0700, [EMAIL PROTECTED] wrote:
 On Aug 30, 12:42 am, Bruno Desthuilliers bruno.
 [EMAIL PROTECTED] wrote:
  [EMAIL PROTECTED] a crit :
 
 
  What's with using your brain instead of whining ?
 
 I knew there would be at least one religious zealot.

While I agree that Bruno's response was perhaps needlessly snippy, your
original question was needlessly inflammatory, as if you somehow wanted
some religious zealot to act the way Bruno did. If we start labeling
people, this thread will earn you a label that rhymes with roll.

-- 
Carsten Haese
http://informixdb.sourceforge.net


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Neil Cerutti
On 2007-08-30, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 How could it not be an exception, in the plain English sense
 of the word? Most certainly you're asking for the index
 because you want to do something with the index. If the item
 is not found, you have no index, so that's a special case that
 must be handled separately. There is no logical difference
 between handling that special case in an except clause versus
 handling it with an if-branch.

 In my case of have done os.listdir() on two directories. I want
 to see what files are in directory A that are not in directory
 B.

In that case list.find would not be much of a win, but sets might
be.

 not_in_both = list(set(os.listdir(A)) - set(os.listdir(B)))

 I have used exceptions in other languages and only do so on
 logic that should never happen. In this case it is known that
 some of the files will not be in both lists. I just want to
 know which ones.

Exceptions has become somewhat a misnomer. iterators are
implemented using exceptions, and there's hardly anything more
common in modern Python code. The hair shirts and thumb-screws
necessary for using exceptions correctly in C++, aren't needed in
Python.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: list index()

2007-08-30 Thread Hamilton, William
 From: [EMAIL PROTECTED]
 
  How could it not be an exception, in the plain English sense of the
  word? Most certainly you're asking for the index because you want to
do
  something with the index. If the item is not found, you have no
index,
  so that's a special case that must be handled separately. There is
no
  logical difference between handling that special case in an except
  clause versus handling it with an if-branch.
 
 In my case of have done os.listdir() on two directories. I want to see
 what files are in directory A that are not in directory B.
 I have used exceptions in other languages and only do so on logic that
 should never happen. In this case it is known that some of the files
 will not be in both lists. I just want to know which ones.
 

I think you may be confusing exceptions and assertions.  Asserts are
generally used to trap conditions that should not happen, while
exceptions in Python are a standardized way to handle errors of all
sorts.  Where in C you would, say, open a file and check the return code
to ensure that the file actually exists before using it, in Python you
wrap the open statement in a try/except block instead.


--
-Bill Hamilton
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread zzbbaadd
 While I agree that Bruno's response was perhaps needlessly snippy, your
 original question was needlessly inflammatory, as if you somehow wanted
 some religious zealot to act the way Bruno did. If we start labeling
 people, this thread will earn you a label that rhymes with roll.

That is correct. I did word it in a way that would hook the Bruno's of
the group. But I will probably have some more important questions so I
will word it differently in the future. Such as: I wish they were not
getting rid of dict.has_key() in Python 3, which I prefer to IN.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread zzbbaadd
Neil, Steve,

Thanks for the responses on sets. I have not used them before and was
not even aware Python had them. I will try them out.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Carsten Haese
On Thu, 2007-08-30 at 11:21 -0700, [EMAIL PROTECTED] wrote:
 I wish they were not
 getting rid of dict.has_key() in Python 3, which I prefer to IN.

That wish will only come true if you maintain your own fork of Python 3.
has_key() will go away, period. It has been made obsolete by in, which
is faster and more concise.

-- 
Carsten Haese
http://informixdb.sourceforge.net


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Steve Holden
[EMAIL PROTECTED] wrote:
 While I agree that Bruno's response was perhaps needlessly snippy, your
 original question was needlessly inflammatory, as if you somehow wanted
 some religious zealot to act the way Bruno did. If we start labeling
 people, this thread will earn you a label that rhymes with roll.

 That is correct. I did word it in a way that would hook the Bruno's of
 the group. But I will probably have some more important questions so I
 will word it differently in the future. Such as: I wish they were not
 getting rid of dict.has_key() in Python 3, which I prefer to IN.
 
 
Well, again Python gives you the flexibility to define your own dict 
subclass that has a has_key() method with the obvious implementation.

But why would you want to ignore built-in support like value in dict?

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread zzbbaadd

 That wish will only come true if you maintain your own fork of Python 3.
 has_key() will go away, period. It has been made obsolete by in, which
 is faster and more concise.

Is there really some reason  key IN dict can be implemented faster
than dict.has_key(key)???



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Neil Cerutti
On 2007-08-30, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 That wish will only come true if you maintain your own fork of
 Python 3. has_key() will go away, period. It has been made
 obsolete by in, which is faster and more concise.

 Is there really some reason  key IN dict can be implemented
 faster than dict.has_key(key)???

Yes. Looking up the has_key method by name is the slower part.

-- 
Neil Cerutti
We're not afraid of challenges. It's like we always say: If you want to go out
in the rain, be prepared to get burned. --Brazillian soccer player
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Chris Mellon
On 8/30/07, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

  That wish will only come true if you maintain your own fork of Python 3.
  has_key() will go away, period. It has been made obsolete by in, which
  is faster and more concise.

 Is there really some reason  key IN dict can be implemented faster
 than dict.has_key(key)???


Yes. As an exercise, I wont tell you the first most obvious reason -
see if you can figure it out. The dis module may help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Carsten Haese
On Thu, 2007-08-30 at 11:45 -0700, [EMAIL PROTECTED] wrote:
  That wish will only come true if you maintain your own fork of Python 3.
  has_key() will go away, period. It has been made obsolete by in, which
  is faster and more concise.
 
 Is there really some reason  key IN dict can be implemented faster
 than dict.has_key(key)???

Yes, see e.g.
http://groups.google.com/group/comp.lang.python/msg/03e9b4276846b9c0

-- 
Carsten Haese
http://informixdb.sourceforge.net


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread MRAB
On Aug 30, 7:00 pm, Steve Holden [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  How could it not be an exception, in the plain English sense of the
  word? Most certainly you're asking for the index because you want to do
  something with the index. If the item is not found, you have no index,
  so that's a special case that must be handled separately. There is no
  logical difference between handling that special case in an except
  clause versus handling it with an if-branch.

  In my case of have done os.listdir() on two directories. I want to see
  what files are in directory A that are not in directory B.
  I have used exceptions in other languages and only do so on logic that
  should never happen. In this case it is known that some of the files
  will not be in both lists. I just want to know which ones.

 And, as is so often the case, once the *real* problem is stated a more
 elegant solution become available - in this case, using sets.

 afiles = set(os.listdir(dira))
 bfiles = set(os.listdir(dirb))

 for f in (afiles - bfiles):
print Not common:, f

 You can also generate the files that are in one directory but ot the
 other with

 (afiles | bfiles) - (afiles  bfiles)

... which can be written more concisely as:

afiles ^ bfiles

:-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread MRAB
On Aug 30, 5:41 pm, [EMAIL PROTECTED] wrote:
 On Aug 30, 12:09 am, Ben Finney [EMAIL PROTECTED]
 wrote:

  [EMAIL PROTECTED] writes:
   What's with the index() function of lists throwing an exception on not
   found?

  It's letting you know that the item isn't in the list. There's no
  sensible return value from an index function in that condition.

 for str:

 find(   sub[, start[, end]])
 Return the lowest index in the string where substring sub is
 found, such that sub is contained in the range [start, end]. Optional
 arguments start and end are interpreted as in slice notation. Return
 -1 if sub is not found.

 -1 is used in other languages as well.

In 0-based languages it's often -1 whereas in 1-based languages it's
often 0.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list index()

2007-08-30 Thread Marc 'BlackJack' Rintsch
On Thu, 30 Aug 2007 09:41:00 -0700, zzbbaadd wrote:

 On Aug 30, 12:09 am, Ben Finney [EMAIL PROTECTED]
 wrote:
 [EMAIL PROTECTED] writes:
  What's with the index() function of lists throwing an exception on not
  found?

 It's letting you know that the item isn't in the list. There's no
 sensible return value from an index function in that condition.
 
 for str:
 
 find( sub[, start[, end]])
 Return the lowest index in the string where substring sub is
 found, such that sub is contained in the range [start, end]. Optional
 arguments start and end are interpreted as in slice notation. Return
 -1 if sub is not found.

But that is a valid index into a string!  So this may go unnoticed if one
doesn't check after every call to `str.find()`.  And that method is going
away in Python 3.0.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

  1   2   >