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
> 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
> zzbb...@aol.com 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
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
> 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
> 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
Yes, you're right. Sorry.
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
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
> 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
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 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 with using your brain instead of whining ?
I knew there would be at least one religious zealot.
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
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 -------------
list.index() is the wrong tool for that job. Python has sets, use them.
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".
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
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
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.
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.
But why would you want to ignore built-in support like "value in dict"?
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
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.
afiles ^ bfiles
:-)
In 0-based languages it's often -1 whereas in 1-based languages it's
often 0.
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
> On Aug 30, 12:09 am, Ben Finney <bignose+hates-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.
--
\ "Hey Homer! You're late for English!" "Pff! English, who needs |
`\ that? I'm never going to England!" -- Barney & Homer, _The |
_o__) Simpsons_ |
Ben Finney
> 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.
You get that information unambiguously. It's an exceptional case,
since there's no index to return, so it throws an exception.
> I have used exceptions in other languages and only do so on logic
> that should never happen.
You're confusing "assert" ("this should always be true") with
"exception" ("this is an exception to the the normal flow of this
process").
An exception isn't "something that should never happen", it's
something that is entirely possible and needs to be handled somehow.
--
\ "Always do right. This will gratify some people, and astonish |
`\ the rest." -- Mark Twain |
_o__) |
Ben Finney
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.
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.
if mylist.contains("hello):
how its defined in Python is what is important in this context.
> 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.
>
> if mylist.contains("hello):
>
Genius. Why didn't anyone think of that before?
> But why would you want to ignore built-in support like "value in dict"?
Because a function can be passed as a value in its own right, a built-in
construct cannot.
Either I'm misunderstanding 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:
Python 1.5.2 (#1, Nov 6 1999, 14:53:40) [C] on sco_sv3
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> if 3 in [1,2,3]: print "Yup, got it!"
...
Yup, got it!
This feature may be older than version 1.5.2, but this is the oldest
version that I still have running anywhere.
...and that's why we have operator.contains():
>>> import operator
>>> help(operator.contains)
Help on built-in function contains in module operator:
contains(...)
contains(a, b) -- Same as b in a (note reversed operands).
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.
def inAnotB(A, B):
inA = os.listdir(A)
inBs = set(os.listdir(B))
return [f for f in inA if f not in inBs]
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)...).
Alex
> zzbb...@aol.com 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.
And what is the order of passing a list into a set? O(N)+?
>
>
> Alex
Roughly O(N), yes (with the usual caveats about hashing costs, &c;-).
So, when A has M files and B has N, your total costs are roughly O(M+N)
instead of O(M*N) -- a really juicy improvement for large M and N!
Alex
Is there a definition on python.org for an exception?
>
> > 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.
>
> > if mylist.contains("hello):
>
> Genius. Why didn't anyone think of that before?
With an attitude like that Chris, don't expect to be getting an invite
to beta test my Python 3 fork.
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
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.
Welcome to comp.lang.python, where laziness is punished with brutal sarcasm.
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:"
Because they do not have exceptions.
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
>>>
> .................. 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
> 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 && m...@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
No need to wait:
>>> 'a' in ['a', 'b']
True
>>> ['a', 'b'].__contains__('a')
True
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.
> 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 && m...@alcyone.com && 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
[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 "o"s sound short to me.
Like "bot" rather than "boat" using your example.
TJG
Welcome to England!
> Which you pronounce _boat_ and _bot_ the same way, too?
No. HTH HAND.
Since we're talking... I'm still a little startled when I listen
to some of the excellent webcasts that are being produced these
days (showmedo.com and friends) and hear American voices pronounce
Python... well, the way they do, with the stress and something of a
drawl on the second syllable. I'm sure it's just as amusing the other
way round: we pronounce it with the stress on the first syllable and
the characteristic short vowel sound in the second.
(Something like: Pie'thun).
TJG
[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
ric...@entrian.com
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.
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. :(
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
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
As for the pronunciation of "Python", let's ask Guido! :-)
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
> ric...@entrian.com
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 -------------
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.
>_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
The only true way of pronouncing Python (the computing language), is
the way it is done at the beginning of Monty Pythons Flying Circus of
course :-)
Your right, the American way does make me pause.
- Paddy.
> On Thu, 2007-08-30 at 11:21 -0700, zzbb...@aol.com 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.
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.
> 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
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.
Same here - when the Troll lives under a bridge - I could not think
of something to rhyme with it - frolic is just right.
- Hendrik
> 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
Where's Godwin's Law when yo need it?
Yep, they would have posted about it way-back if they had the tech...
http://uk.youtube.com/watch?v=zZ3fjQa5Hls
(Gershwin doesn't seem to have a line about troll though :-)
- Paddy.
> 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 "i"s.
--
\ "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
No difference. A troll is a troll is a troll.
:-)
- Paddy.
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.
> Dennis Lee Bieber <wlf...@ix.netcom.com> 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 "i"s.
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.
> 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
> Where's Godwin's Law when yo need it?
Hitler would not have spellt "you" like that...
- Hendrik
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.
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...)
> 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('~ooiirnncc@-kk.og'),key=lambda a:a[1]),0)[1:]
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.
> 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
> 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
> 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
"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
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"