473,836 Members | 1,438 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 4629
In message <87************ @benfinney.id.a u>, Ben Finney wrote:
zz******@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.
How about returning None? That's what's already done by the dict.get method
by default.
Aug 31 '07 #41
Either I'm misunderstandin g what you mean or you need to get a clue
about what Python can already do before you go around making suggestions
for what Python needs. Lists have supported "in" tests since at least
version 1.5.2:
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().

Aug 31 '07 #42
On Aug 30, 9:26 pm, al...@mac.com (Alex Martelli) wrote:
<zzbba...@aol.c omwrote:

...
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.

So why would you care about WHERE, in the listdir of B, are to be found
the files that are in A but not B?! You should call .index only if you
CARE about the position.
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)...).
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)
?

>
Alex

Aug 31 '07 #43
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.

--
Carsten Haese
http://informixdb.sourceforge.net
Aug 31 '07 #44
On Aug 30, 9:06 pm, "Carsten Haese" <cars...@uniqsy s.comwrote:
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:"

Aug 31 '07 #45

"Marc 'BlackJack' Rintsch" <bj****@gmx.net wrote in message
news:5j******** ***@mid.uni-berlin.de...
| On Thu, 30 Aug 2007 17:09:36 +1000, Ben Finney wrote:
|
| zz******@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.
|
| What about -1? C programmers do this all the time. :-)

Because they do not have exceptions.

Aug 31 '07 #46
zz******@aol.co m a écrit :
On Aug 30, 4:28 pm, Ben Finney <bignose+hate s-s...@benfinney. id.au>
wrote:
>zzbba...@aol.c om writes:
>>On Aug 30, 12:09 am, Ben Finney <bignose+hate s-s...@benfinney. id.au>
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
>>>
Aug 31 '07 #47
"Carsten Haese" <car...ys.comwr ote:
............... ... 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

Aug 31 '07 #48
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 && ma*@alcyone.com && 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
Aug 31 '07 #49
zz******@aol.co m 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
Aug 31 '07 #50

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

Similar topics

5
1489
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
17429
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
28503
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
29249
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
10815
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
2429
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
3772
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
18878
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
4392
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
10541
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...
0
9367
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...
1
7785
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6976
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5645
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...
0
5818
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4447
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
2
4007
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3108
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.