473,597 Members | 2,258 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

list index()

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.

Aug 30 '07
96 4534
zz******@aol.co m 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

Aug 30 '07 #11
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
Aug 30 '07 #12
On Aug 30, 12:09 am, Ben Finney <bignose+hate s-s...@benfinney. id.au>
wrote:
zzbba...@aol.co m 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.

Aug 30 '07 #13
>
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.

Aug 30 '07 #14
On Aug 30, 12:42 am, Bruno Desthuilliers <bruno.
42.desthuilli.. .@wtf.websitebu ro.oops.comwrot e:
zzbba...@aol.co m a écrit :
What's with using your brain instead of whining ?
I knew there would be at least one religious zealot.
Aug 30 '07 #15
zz******@aol.co m 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

Aug 30 '07 #16
zz******@aol.co m 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 -------------

Aug 30 '07 #17
On Thu, 2007-08-30 at 10:44 -0700, zz******@aol.co m 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
Aug 30 '07 #18
On Thu, 2007-08-30 at 10:56 -0700, zz******@aol.co m wrote:
On Aug 30, 12:42 am, Bruno Desthuilliers <bruno.
42.desthuilli.. .@wtf.websitebu ro.oops.comwrot e:
zzbba...@aol.co m 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
Aug 30 '07 #19
On 2007-08-30, zz******@aol.co m <zz******@aol.c omwrote:
>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.lis tdir("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
Aug 30 '07 #20

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

Similar topics

5
1480
by: questions? | last post by:
I want to do list index function. >>> y= >>> y >>> y.index Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: unsubscriptable object It works with y=. Anyone has any hint, what's the reason
9
17397
by: William Meyer | last post by:
hi, I need to get the index of an object in a list. I know that no two objects in the list are the same, but objects might evaluate as equal. for example list = for object in list: objectIndex = list.index(object) print objectIndex
8
28472
by: sam | last post by:
hey everybody, this is my first time posting here. i'm pretty new to python and programming in general (as you'll soon work out for yourselves...) i'm trying to code a version of a selection sort and the heart of the code is as follows (no_lines is simply the number of items to be sorted, read out of an input file): for j in range(0, no_lines):
35
29204
by: erikwickstrom | last post by:
Hi all, I'm sorry about the newbie question, but I've been searching all afternoon and can't find the answer! I'm trying to get this bit of code to work without triggering the IndexError. import shutil, os, sys
7
10772
by: python101 | last post by:
My code s= for k in range(len(s)): st=s.count(s) if st>=2: print s.pop(s.index(s)) Traceback (most recent call last):
3
2411
by: Riccardo Murri | last post by:
Hello, I have some code that stops when trying to find a graph in a list of similar graphs:: (Pydb) list 110 try: 111 canonical = self.base 112 except ValueError: 113 raise ValueError, \
2
3716
by: Georgy Panterov | last post by:
I am a relatively new python user. I am writing an economic simulation of acard-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 sometimesfor 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...
5
18644
by: Mr.SpOOn | last post by:
Hi, is there any way to search elements in a list using wildcards? I have a list of various elements and I need to search for elements starting with 'no', extract them and put in a new list. I was thinking about something like: mylist.index('no*') Of course this doesn't work.
2
4379
by: Chriskim | last post by:
I wrote a program that uses PyQt4, mathplotlib to generates graphs. I made a executable file using Py2exe. Everything is working fine, but when I exit from my program, a window message pops out and tells me to look at the log file. In the log file, here is what they said C:\Users\dmckinnon\Desktop\ChrisKim\eSimulator_original\src\dist\library.zip\matplotlib\__init__.py:572: UserWarning: Could not find matplotlibrc; using defaults...
0
7887
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8274
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8381
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8036
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6695
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
3886
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2404
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1494
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1241
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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

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