> On Wed, Sep 5, 2012 at 3:11 PM, Stephen Anto <charvigro...@gmail.com> wrote:
>> On Wed, Sep 5, 2012 at 2:10 PM, Kushal Kumaran
>> <kushal.kumaran+pyt...@gmail.com> wrote:
>>> On Wed, Sep 5, 2012 at 12:20 PM, <charvigro...@gmail.com> wrote:
>>> > On Tuesday, October 30, 2007 11:44:01 PM UTC+5:30, Krypto wrote:
>>> >> Hi,
>>> >> I have used Python for a couple of projects last year and I found it
>>> >> extremely useful. I could write two middle size projects in 2-3 months
>>> >> (part time). Right now I am a bit rusty and trying to catch up again
>>> >> with Python.
>>> >> I am now appearing for Job Interviews these days and I am wondering if
>>> >> anybody of you appeared for a Python Interview. Can you please share
>>> >> the questions you were asked. That will be great help to me.
>>> > Finally I have decided to put best interview question and answers.
>>> As I see from a quick glance, several of your answers seem to be
>>> copied from the python faq at http://docs.python.org/faq/. The
>>> copyright notice for the python.org website seems to be at
>>> http://docs.python.org/copyright.html. Do you have the Python
>>> Software Foundation's permission to copy large chunks of the
>>> python.org website and claim it as your own content?
>> Thank you for your information, I really sorry for this, if possible could
>> you note which are the questions taken from faq, we will remove it as early
>> as possible.
> Since your website's Terms of Use state that you own the content, it
> is your problem to make sure whatever's there is there legally.
> Here's one example, though, to get you started: See the entry "Why
> can’t I use an assignment in an expression?" at
> http://docs.python.org/faq/design.html, and compare with the content
> under the identical heading on page 3 of the CorePython section.
On Sat, 17 Nov 2012 10:01:01 -0800, chinjannisha wrote:
> Hi I had one doubt.. I know very little bit of python .I wanted to know
> when to use list,tuple,dictionary and set? Please reply me asap
Use a list when you want a list of items that should all be treated the same way:
list_of_numbers = [1, 3, 5.1, 2, 6.5]
total = sum(list_of_numbers)
or when you need a collection of items where the order they are in is important:
winners = ['george', 'susan', 'henry'] # 1st, 2nd, 3rd place
print('The winner is:', winners[0])
Use a tuple when you want a collection of items that mean different things, a bit like a C struct or Pascal record:
a = (23, "henry", True, 'engineer')
b = (42, "natalie", False, 'manager')
c = (17, "george", True, 'student')
Use a dict when you need a collection of key:value mappings:
In article <50a8acdc$0$29978$c3e8da3$54964...@news.astraweb.com>,
Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote:
> Use a list when you want a list of items that should all be treated the > same way [...] or when you need a collection of items where the order they are in is > important:
> Use a tuple when you want a collection of items that mean different > things, a bit like a C struct or Pascal record:
That is certainly the right answer according to the One True Church Of Pythonic Orthodoxy And Theoretical Correctness. But, let me give an alternative answer which works for The Unwashed Masses Who Live In The Trenches And Write Python Code For A Living:
Use a list when you need an ordered collection which is mutable (i.e. can be altered after being created). Use a tuple when you need an immutable list (such as for a dictionary key).
On Sun, 18 Nov 2012 08:53:25 -0500, Roy Smith wrote:
> In article <50a8acdc$0$29978$c3e8da3$54964...@news.astraweb.com>,
> Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote:
>> Use a list when you want a list of items that should all be treated the
>> same way [...] or when you need a collection of items where the order
>> they are in is important:
>> Use a tuple when you want a collection of items that mean different
>> things, a bit like a C struct or Pascal record:
> That is certainly the right answer according to the One True Church Of
> Pythonic Orthodoxy And Theoretical Correctness.
Oh I'm sorry, did something I say suggest that the couple of examples I gave are the *only* acceptable uses? My apologies for not giving an exhaustive list of every possible use of lists and tuples, I'll be sure to punish myself severely for the lapse.
> But, let me give an
> alternative answer which works for The Unwashed Masses Who Live In The
> Trenches And Write Python Code For A Living:
> Use a list when you need an ordered collection which is mutable (i.e.
> can be altered after being created). Use a tuple when you need an
> immutable list (such as for a dictionary key).
I keep hearing about this last one, but I wonder... who *actually* does this? I've created many, many lists over the years -- lists of names, lists of phone numbers, lists of directory search paths, all sorts of things. I've never needed to use one as a dictionary key.
Under what sort of circumstances would somebody want to take a mutable list of data, say a list of email addresses, freeze it into a known state, and use that frozen state as a key in a dict? What would be the point? Even if there was some meaningful reason to look up "this list of 12000 email addresses" as a single key, it is going to get out of sync with the actual mutable list.
Sure, I have built a collection of items as a list, because lists are mutable, then frozen it into a tuple, and *thrown the list away*, then used the tuple as a key. But that's not the same thing, the intent is different. In my case, the data was never intended to be a list, it was always intended to be a fixed record-like collection, the use of list was as a temporary data structure used for construction. A bit like the idiom of ''.join(some_list).
But I can't think of any meaningful, non-contrived example where I might want an actual mutable list of values as a dict key.
Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote:
> On Sun, 18 Nov 2012 08:53:25 -0500, Roy Smith wrote:
>> > Use a list when you need an ordered collection which is mutable
> > (i.e. can be altered after being created). Use a tuple when you
> > need an immutable list (such as for a dictionary key).
> I keep hearing about this last one, but I wonder... who *actually*
> does this? I've created many, many lists over the years -- lists of
> names, lists of phone numbers, lists of directory search paths, all
> sorts of things. I've never needed to use one as a dictionary key.
-- D'Arcy J.M. Cain <da...@druid.net> | Democracy is three wolves
http://www.druid.net/darcy/ | and a sheep voting on
+1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner.
IM: da...@Vex.Net
In article <50a911ec$0$29978$c3e8da3$54964...@news.astraweb.com>,
Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote:
> Oh I'm sorry, did something I say suggest that the couple of examples I > gave are the *only* acceptable uses? My apologies for not giving an > exhaustive list of every possible use of lists and tuples, I'll be sure > to punish myself severely for the lapse.
Hmmm. I didn't mean any offense. I was just pointing out that what's true in theory and what's true in practice aren't always the same.
> Under what sort of circumstances would somebody want to take a mutable > list of data, say a list of email addresses, freeze it into a known > state, and use that frozen state as a key in a dict?
I've got a script which trolls our log files looking for python stack dumps. For each dump it finds, it computes a signature (basically, a call sequence which led to the exception) and uses this signature as a dictionary key. Here's the relevant code (abstracted slightly for readability):
def main(args):
crashes = {}
[...]
for line in open(log_file):
if does_not_look_like_a_stack_dump(line):
continue
lines = traceback_helper.unfold(line)
header, stack = traceback_helper.extract_stack(lines)
signature = tuple(stack)
if signature in crashes:
count, header = crashes[signature]
crashes[signature] = (count + 1, header)
else:
crashes[signature] = (1, header)
> On 18 Nov 2012 16:50:52 GMT
> Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote:
>> On Sun, 18 Nov 2012 08:53:25 -0500, Roy Smith wrote:
>>> > Use a list when you need an ordered collection which is mutable
>> > (i.e. can be altered after being created). Use a tuple when you
>> > need an immutable list (such as for a dictionary key).
>> I keep hearing about this last one, but I wonder... who *actually*
>> does this? I've created many, many lists over the years -- lists of
>> names, lists of phone numbers, lists of directory search paths, all
>> sorts of things. I've never needed to use one as a dictionary key.
That's a structure, not a list. Every key will consist of precisely
three values: two integers and one keyword string. Already covered by
a previous example.
On Sun, 18 Nov 2012 12:53:50 -0500, Roy Smith wrote:
> I've got a script which trolls our log files looking for python stack
> dumps. For each dump it finds, it computes a signature (basically, a
> call sequence which led to the exception) and uses this signature as a
> dictionary key. Here's the relevant code (abstracted slightly for
> readability):
> def main(args):
> crashes = {}
> [...]
> for line in open(log_file):
> if does_not_look_like_a_stack_dump(line):
> continue
> lines = traceback_helper.unfold(line)
> header, stack = traceback_helper.extract_stack(lines)
> signature = tuple(stack)
> if signature in crashes:
> count, header = crashes[signature]
> crashes[signature] = (count + 1, header)
> else:
> crashes[signature] = (1, header)
> The stack that's returned is a list. It's inherently a list, per the
> classic definition:
Er, no, it's inherently a blob of multiple text lines. Sure, you've built it a line at a time by using a list, but I've already covered that case. Once you've identified a stack, you never append to it, sort it, delete lines in the middle of it... none of these list operations are meaningful for a Python stack trace. The stack becomes a fixed string, and not just because you use it as a dict key, but because inherently it counts as a single, immutable blob of lines.
A tuple of individual lines is one reasonable data structure for a blob of lines. Another would be a single string:
signature = '\n'.join(stack)
Depending on what you plan to do with the signatures, one or the other implementation might be better. I'm sure that there are other data structures as well.
> * It's variable length. Different stacks have different depths.
Once complete, the stack trace is fixed length, but that fixed length is different from one stack to the next. Deleting a line would make it incomplete, and adding a line would make it invalid.
> * It's homogeneous. There's nothing particularly significant about each
> entry other than it's the next one in the stack.
> * It's mutable. I can build it up one item at a time as I discover
> them.
The complete stack trace is inhomogeneous and immutable. I've already covered immutability above: removing, adding or moving lines will invalidate the stack trace. Inhomogeneity comes from the structure of a stack trace. The mere fact that each line is a string does not mean that any two lines are equivalent. Different lines represent different things.
Traceback (most recent call last):
File "./prattle.py", line 873, in select
selection = self.do_callback(cb, response)
File "./prattle.py", line 787, in do_callback
raise callback
ValueError: what do you mean?
is a valid stack. But:
Traceback (most recent call last):
raise callback
selection = self.do_callback(cb, response)
File "./prattle.py", line 787, in do_callback
ValueError: what do you mean?
File "./prattle.py", line 873, in select
is not. A stack trace has structure. The equivalent here is the difference between:
But there's really nothing you can do about the immutability. There isn't any meaningful reason why you might want to take a complete stack trace and add or delete lines from it.
[it doesn't really have ...'s in the paths; I just elided some text to make it easier to read]
> > * It's homogeneous. There's nothing particularly significant about each
> > entry other than it's the next one in the stack.
> The complete stack trace is inhomogeneous and immutable. I've already > covered immutability above: removing, adding or moving lines will > invalidate the stack trace. Inhomogeneity comes from the structure of a > stack trace. The mere fact that each line is a string does not mean that > any two lines are equivalent. Different lines represent different things.
No. Each entry in the list represents a source file and a function name. They're all the same "shape". You could remove one or add another one, or shuffle the order, and you would have something which was syntactically correct and semantically meaningful (even if it didn't represent an actual code path.
> - drop the Traceback line and the final exception line;
> - parse the File lines to extract the useful fields;
> - combine them with the source code.
You mean, kind of like the code I cited does? :-)
I think we're going to have to let this be. You obviously have your concept of what a tuple is and what a list is. I disagree. I don't think either of us is right or wrong, we just have different ways of thinking about things.
You come at it from a theoretical point of view. You think of each type as an embodiment of certain concepts ("it represents a fixed-length heterogenous sequence"). Your thinking is driven by what each type was intended to be used for.
I come at it from a practical point of view. To me, each type is a collection of methods. I have certain operations I need to perform. I pick the type which offers those operations. If the set of operations I need to perform (in this case, {append, hash}) don't exist in a single type, I'm forced to use both types and convert from one to the other as needed.
The theorist understands that a chisel and a screwdriver were intended for different purposes, but the pragmatist gets the paint can open.
On Mon, Nov 19, 2012 at 1:09 PM, Roy Smith <r...@panix.com> wrote:
> The theorist understands that a chisel and a screwdriver were intended
> for different purposes, but the pragmatist gets the paint can open.
A good tool can always be used in ways its inventor never intended -
and it will function as its user expects.
$ some_program | egrep --color=always '(ERROR|^)'
will highlight the word ERROR in red anywhere it appears in the
program's output, while maintaining all other lines without color. Not
normal use of grep, to be sure, but quite functional.
A tuple may have been intended to be a record, a struct, whatever, but
it is what it is, and I'll use one any time it's the best tool for the
job. Maybe its immutability is critical; or maybe it's just the most
convenient syntax and all I care about is that it be iterable.
But when I'm explaining grep to someone, I'll describe it as a filter
that keeps only some lines from the original, and when I describe a
tuple, I'll point out that it's immutable and (potentially) hashable.
The obvious first, the unobvious later.
> The theorist understands that a chisel and a screwdriver were intended
> for different purposes, but the pragmatist gets the paint can open.
To throw a chiseldriver into the works, IIRC a tuple is way faster to create but accessing a list is much faster. The obvious snag is that may have been Python 2.7 whereas 3.3 is completely different. Sorry but I'm currently wearing my XXXL size Lazy Bone Idle Hat so have no figures to back my probably incorrect memory up, anyone know anything about this?
On Sun, Nov 18, 2012 at 7:42 PM, Mark Lawrence <breamore...@yahoo.co.uk> wrote:
> To throw a chiseldriver into the works, IIRC a tuple is way faster to create
> but accessing a list is much faster. The obvious snag is that may have been
> Python 2.7 whereas 3.3 is completely different. Sorry but I'm currently
> wearing my XXXL size Lazy Bone Idle Hat so have no figures to back my
> probably incorrect memory up, anyone know anything about this?
It's not been my experience with Python 2.7 that list access is faster
than tuple access. Tuples are as fast as or faster than lists, pretty
much universally. They seem to have closed the gap a bit in
Python 3.3, though, as the following timings show. For one-shot
construction, tuples seem to be more efficient for short sequences,
but then lists win for longer sequences, although not by much. Of
course, lists are always going to be much slower if you build them up
with appends and extends.
C:\>python -m timeit -s "x = range(10)" "tuple(x)"
1000000 loops, best of 3: 0.773 usec per loop
C:\>python -m timeit -s "x = range(10)" "list(x)"
1000000 loops, best of 3: 0.879 usec per loop
C:\>python -m timeit -s "x = range(100)" "tuple(x)"
100000 loops, best of 3: 2.88 usec per loop
C:\>python -m timeit -s "x = range(100)" "list(x)"
100000 loops, best of 3: 2.63 usec per loop
C:\>python -m timeit -s "x = range(1000)" "tuple(x)"
10000 loops, best of 3: 37.4 usec per loop
C:\>python -m timeit -s "x = range(1000)" "list(x)"
10000 loops, best of 3: 36.2 usec per loop
C:\>python -m timeit -s "x = range(10000)" "tuple(x)"
1000 loops, best of 3: 418 usec per loop
C:\>python -m timeit -s "x = range(10000)" "list(x)"
1000 loops, best of 3: 410 usec per loop
For iteration, tuples are consistently 7-8% faster.
C:\>python -m timeit -s "x = tuple(range(10))" "for i in x: pass"
1000000 loops, best of 3: 0.467 usec per loop
C:\>python -m timeit -s "x = list(range(10))" "for i in x: pass"
1000000 loops, best of 3: 0.498 usec per loop
C:\>python -m timeit -s "x = tuple(range(100))" "for i in x: pass"
100000 loops, best of 3: 3.31 usec per loop
C:\>python -m timeit -s "x = list(range(100))" "for i in x: pass"
100000 loops, best of 3: 3.56 usec per loop
C:\>python -m timeit -s "x = tuple(range(1000))" "for i in x: pass"
10000 loops, best of 3: 31.6 usec per loop
C:\>python -m timeit -s "x = list(range(1000))" "for i in x: pass"
10000 loops, best of 3: 34.3 usec per loop
C:\>python -m timeit -s "x = tuple(range(10000))" "for i in x: pass"
1000 loops, best of 3: 318 usec per loop
C:\>python -m timeit -s "x = list(range(10000))" "for i in x: pass"
1000 loops, best of 3: 341 usec per loop
For direct item access, tuples seem to be about 2-3% faster.
C:\>python -m timeit -s "import operator as o; x = tuple(range(10)); g
= o.itemgetter(*range(len(x)))" "g(x)"
1000000 loops, best of 3: 0.67 usec per loop
C:\>python -m timeit -s "import operator as o; x = list(range(10)); g
= o.itemgetter(*range(len(x)))" "g(x)"
1000000 loops, best of 3: 0.674 usec per loop
C:\>python -m timeit -s "import operator as o; x = tuple(range(100));
g = o.itemgetter(*range(len(x)))" "g(x)"
100000 loops, best of 3: 4.52 usec per loop
C:\>python -m timeit -s "import operator as o; x = list(range(100)); g
= o.itemgetter(*range(len(x)))" "g(x)"
100000 loops, best of 3: 4.65 usec per loop
C:\>python -m timeit -s "import operator as o; x = tuple(range(1000));
g = o.itemgetter(*range(len(x)))" "g(x)"
10000 loops, best of 3: 43.2 usec per loop
C:\>python -m timeit -s "import operator as o; x = list(range(1000));
g = o.itemgetter(*range(len(x)))" "g(x)"
10000 loops, best of 3: 43.7 usec per loop
C:\>python -m timeit -s "import operator as o; x =
tuple(range(10000)); g = o.itemgetter(*range(len(x)))" "g(x)"
1000 loops, best of 3: 422 usec per loop
C:\>python -m timeit -s "import operator as o; x = list(range(10000));
g = o.itemgetter(*range(len(x)))" "g(x)"
1000 loops, best of 3: 447 usec per loop
On Sun, 18 Nov 2012 21:09:36 -0500, Roy Smith wrote:
> In article <50a97de0$0$29983$c3e8da3$54964...@news.astraweb.com>,
> Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote:
>> > The stack that's returned is a list. It's inherently a list, per the
>> > classic definition:
>> Er, no, it's inherently a blob of multiple text lines.
> No, it's a list that looks like (taken from the doc string of the code I
> referenced):
> [it doesn't really have ...'s in the paths; I just elided some text to
> make it easier to read]
I see. It wasn't clear from your earlier description that the items had been post-processed from collections of raw log lines to fixed records. But it doesn't actually change my analysis any. See below.
By the way, based on the sample data you show, your script is possibly broken. You don't record either the line number that raises, or the exception raised, so your script doesn't differentiate between different errors that happen to occur with similar stack traces. (I say "possibly" broken because I don't know what your requirements are. Maybe your requirements are sufficiently wide that you don't care that distinct failures are counted together.)
E.g. these three stack traces will probably generate the same fixed record, even though the errors are distinct:
#1
Traceback (most recent call last):
File "./spam.py", line 20, in select
selection = func(a, b)
File "./spam.py", line 60, in func
return 1/x
ZeroDivisionError: float division
#2
Traceback (most recent call last):
File "./spam.py", line 20, in select
selection = func(a, b)
File "./spam.py", line 60, in func
return 1/x
TypeError: unsupported operand type(s) for /: 'int' and 'NoneType'
#3
Traceback (most recent call last):
File "./spam.py", line 20, in select
selection = func(a, b)
File "./spam.py", line 55, in func
y = 1/(a + b)
ZeroDivisionError: float division
Maybe that's okay for your application, but it strikes me as odd that you do distinguish *some* distinct errors in the same function, but not others.
>> > * It's homogeneous. There's nothing particularly significant about
>> > each entry other than it's the next one in the stack.
>> The complete stack trace is inhomogeneous and immutable. I've already
>> covered immutability above: removing, adding or moving lines will
>> invalidate the stack trace. Inhomogeneity comes from the structure of a
>> stack trace. The mere fact that each line is a string does not mean
>> that any two lines are equivalent. Different lines represent different
>> things.
> No. Each entry in the list represents a source file and a function
> name. They're all the same "shape". You could remove one or add
> another one, or shuffle the order, and you would have something which
> was syntactically correct and semantically meaningful (even if it didn't
> represent an actual code path.
If you remove/add/shuffle lines in the stack, you no longer have the same stack. Take the example you gave before:
Since they are different stacks, they are treated as different keys:
data = {stack1: 11, stack2: 22}
Do you agree that this is what your application expects? Different stack traces are different keys, associated with different values.
I claim this only makes sense if you treat the stacks as inherently immutable. Never mind Python's limitation. Let's pretend we were running this code under some other language, NeoPython, which allowed mutable keys.
You claim that stacks are *inherently mutable*. So I should be able to do this:
stack1.sort() # it's the *same stack*, all I've done is mutate it
print data[stack1]
and expect to see "11" printed. I am looking at the same key, right? So I certainly don't expect to see the value associated with a completely different key.
But wait a minute... after sorting, stack1 and stack2 now are equal. I could just as easily expect to see "22" printed.
I thought we had just agreed that stack1 and stack2 are *different* keys. Of course they are different. They represent different code paths. But after sorting stack1, it looks exactly like stack2. It looks like a different code path. It *lies* -- it no longer represents the code path that it actually represents, instead it looks like a *different* code path.
should data[stack3] return 11 (it has the same value as stack1) or 22 (it has the same value as stack2)? Or possibly 33? Or raise KeyError?
Treating stacks in this context as mutable is *incoherent*. It is nice and convenient to be able to build up a stack trace using a mutable list, you won't get an argument from me about that, but that can only be considered a temporary data structure used to build the data structure you actually care about, which is fixed.
That brings it back to my question: your application is not a counter-
example to my question about using lists as keys, because your data is not inherently list-like. It is inherently tuple-like, you just build it using a temporary list. That's perfectly fine, by the way, I do the same thing.
As you say, the order of the lines in the stack trace is significant. You cannot expect to mutate the stack and move lines around and treat it as the same stack. If you move the lines about, it represents a different stack. That is fundamentally different from the normal use of a list, where you do expect to be able to move lines about and still have it count as "the same list".
> I think we're going to have to let this be. You obviously have your
> concept of what a tuple is and what a list is. I disagree.
I think a tuple is an immutable sequence of items, and a list is a mutable sequence of items.
> I don't
> think either of us is right or wrong, we just have different ways of
> thinking about things.
> You come at it from a theoretical point of view.
I certainly do not. My position here is imminently practical. The alternative, the mutability of keys, is simply incoherent.
> You think of each type
> as an embodiment of certain concepts ("it represents a fixed-length
> heterogenous sequence"). Your thinking is driven by what each type was
> intended to be used for.
Not even close. My thinking is driven by the things each data structure needs to do. See below.
> I come at it from a practical point of view. To me, each type is a
> collection of methods. I have certain operations I need to perform. I
> pick the type which offers those operations. If the set of operations I
> need to perform (in this case, {append, hash}) don't exist in a single
> type, I'm forced to use both types and convert from one to the other as
> needed.
I don't see that as a problem. Converting from one type to another is exactly the sort of thing I described in my earlier question.
In your application, you build up a collection of code lines that represent a stack trace. Here's that example from your own documentation again:
What are the sorts of things I might meaningfully want to do with this *complete* stack trace?
Add extra lines to it? No. If I needed to add extra lines, it wouldn't be complete.
Delete lines? Certainly not, that would change the code path it claims to represent to a code path it doesn't represent.
Sort the list? Reverse it? Heavens no.
If you look at the available list methods, *not one* of the mutating methods is appropriate to a completed stack trace object. *None* of the mutator list methods are appropriate once the stack trace object is complete, and using them would be counter-productive.
If you believe different, then please tell me what mutations your code actually performs after the stack trace object is completed. In the code you showed, you throw the list away after turning it into a tuple.
If the object represents a "list of code lines", in the sense of a mutable Python list rather than a mere sequence, then why don't you use any list methods on it?
The append method is useful during construction, but that is all. After the stack is complete, use of any mutator method would be a bug. In other words, it ought to be immutable, and the use of a list ought to be buried in the appropriate function as an internal implementation detail. The public interface ought to be that of an immutable tuple of immutable strings, because once you have finished building the object, it should not be possible to mutate it.
This is hardly a theoretical viewpoint. The idea of treating data that ought not be changed as immutable is borne out of bitter experience of millions
> than tuple access. Tuples are as fast as or faster than lists, pretty
> much universally. They seem to have closed the gap a bit in
> Python 3.3, though, as the following timings show. For one-shot
> construction, tuples seem to be more efficient for short sequences,
> but then lists win for longer sequences, although not by much. Of
> course, lists are always going to be much slower if you build them up
> with appends and extends.
Interesting results. But what system (hardware, os). These sorts of times tend to vary with the system.
> C:\>python -m timeit -s "x = range(10)" "tuple(x)"
> 1000000 loops, best of 3: 0.773 usec per loop
> C:\>python -m timeit -s "x = range(10)" "list(x)"
> 1000000 loops, best of 3: 0.879 usec per loop
> C:\>python -m timeit -s "x = range(100)" "tuple(x)"
> 100000 loops, best of 3: 2.88 usec per loop
> C:\>python -m timeit -s "x = range(100)" "list(x)"
> 100000 loops, best of 3: 2.63 usec per loop
> C:\>python -m timeit -s "x = range(1000)" "tuple(x)"
> 10000 loops, best of 3: 37.4 usec per loop
> C:\>python -m timeit -s "x = range(1000)" "list(x)"
> 10000 loops, best of 3: 36.2 usec per loop
> C:\>python -m timeit -s "x = range(10000)" "tuple(x)"
> 1000 loops, best of 3: 418 usec per loop
> C:\>python -m timeit -s "x = range(10000)" "list(x)"
> 1000 loops, best of 3: 410 usec per loop
> For iteration, tuples are consistently 7-8% faster.
> C:\>python -m timeit -s "x = tuple(range(10))" "for i in x: pass"
> 1000000 loops, best of 3: 0.467 usec per loop
> C:\>python -m timeit -s "x = list(range(10))" "for i in x: pass"
> 1000000 loops, best of 3: 0.498 usec per loop
> C:\>python -m timeit -s "x = tuple(range(100))" "for i in x: pass"
> 100000 loops, best of 3: 3.31 usec per loop
> C:\>python -m timeit -s "x = list(range(100))" "for i in x: pass"
> 100000 loops, best of 3: 3.56 usec per loop
> C:\>python -m timeit -s "x = tuple(range(1000))" "for i in x: pass"
> 10000 loops, best of 3: 31.6 usec per loop
> C:\>python -m timeit -s "x = list(range(1000))" "for i in x: pass"
> 10000 loops, best of 3: 34.3 usec per loop
> C:\>python -m timeit -s "x = tuple(range(10000))" "for i in x: pass"
> 1000 loops, best of 3: 318 usec per loop
> C:\>python -m timeit -s "x = list(range(10000))" "for i in x: pass"
> 1000 loops, best of 3: 341 usec per loop
> For direct item access, tuples seem to be about 2-3% faster.
> C:\>python -m timeit -s "import operator as o; x = tuple(range(10)); g
> = o.itemgetter(*range(len(x)))" "g(x)"
> 1000000 loops, best of 3: 0.67 usec per loop
> C:\>python -m timeit -s "import operator as o; x = list(range(10)); g
> = o.itemgetter(*range(len(x)))" "g(x)"
> 1000000 loops, best of 3: 0.674 usec per loop
> C:\>python -m timeit -s "import operator as o; x = tuple(range(100));
> g = o.itemgetter(*range(len(x)))" "g(x)"
> 100000 loops, best of 3: 4.52 usec per loop
> C:\>python -m timeit -s "import operator as o; x = list(range(100)); g
> = o.itemgetter(*range(len(x)))" "g(x)"
> 100000 loops, best of 3: 4.65 usec per loop
> C:\>python -m timeit -s "import operator as o; x = tuple(range(1000));
> g = o.itemgetter(*range(len(x)))" "g(x)"
> 10000 loops, best of 3: 43.2 usec per loop
> C:\>python -m timeit -s "import operator as o; x = list(range(1000));
> g = o.itemgetter(*range(len(x)))" "g(x)"
> 10000 loops, best of 3: 43.7 usec per loop
> C:\>python -m timeit -s "import operator as o; x =
> tuple(range(10000)); g = o.itemgetter(*range(len(x)))" "g(x)"
> 1000 loops, best of 3: 422 usec per loop
> C:\>python -m timeit -s "import operator as o; x = list(range(10000));
> g = o.itemgetter(*range(len(x)))" "g(x)"
> 1000 loops, best of 3: 447 usec per loop
In article <50a9e5cf$0$21863$c3e8da3$76491...@news.astraweb.com>,
Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote:
> I see. It wasn't clear from your earlier description that the items had > been post-processed from collections of raw log lines to fixed records.
Well, I did provide the code that does this.
> But it doesn't actually change my analysis any. See below.
> By the way, based on the sample data you show, your script is possibly > broken. You don't record either the line number that raises, or the > exception raised, so your script doesn't differentiate between different > errors that happen to occur with similar stack traces.
You really might want to read the code I provided. Here's the reference again:
The "header" referred to does indeed contain the exception raised. And the line numbers are included. Here's a typical output stanza:
2012-11-19T00:00:15+00:00 web5 ˇ˛2012-11-19 00:00:15,831 [2712]: songza-api IGPhwNU2SJ691cx8 4C0ABFA9-50A974E7-384995 W6D-HSO 173.145.137.54 songza.django.middleware ERROR process_exception() Path = u'/api/1/station/1459775/next', Exception = ValueError(u"<SequentialSongPicker: <Station 1459775: u'Old School 105.3'>>: no song ids for mp3",)
/home/songza/env/python/local/lib/python2.7/site-packages/django/core/han
dlers/base.py:111:get_response()
/home/songza/deploy/current/pyza/djapi/decorators.py:11:_wrapped_view_fun
c()
/home/songza/env/python/local/lib/python2.7/site-packages/django/views/de
corators/http.py:45:inner()
/home/songza/deploy/current/pyza/djapi/views.py:1659:station_next()
/home/songza/deploy/current/pyza/models/station.py:660:next_song()
/home/songza/deploy/current/pyza/lib/song_picker.py:327:pick()
> I say "possibly" broken because I don't know what your requirements are.
Our requirements are to scan the logs of a production site and filter down the gobs and gobs of output (we produced 70 GB of log files yesterday) into something small enough that a human can see what the most common failures were. The tool I wrote does that.
The rest of this conversation is just silly. It's turning into getting hit on the head lessons.
OK, I've just read back over the whole thread. I'm really struggling to understand what point you're trying to make. I started out by saying:
> Use a list when you need an ordered collection which is mutable (i.e. > can be altered after being created). Use a tuple when you need an > immutable list (such as for a dictionary key).
To which you obviously objected. So now you write:
> I think a tuple is an immutable sequence of items, and a list is a > mutable sequence of items.
So how is that different from what I said? Is this whole argument boiling down to your use of "immutable sequence" vs. my use of "immutable list"?
On Mon, Nov 19, 2012 at 7:30 AM, Roy Smith <r...@panix.com> wrote:
> In article <50a9e5cf$0$21863$c3e8da3$76491...@news.astraweb.com>,
> Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote:
>> By the way, based on the sample data you show, your script is possibly
>> broken. You don't record either the line number that raises, or the
>> exception raised, so your script doesn't differentiate between different
>> errors that happen to occur with similar stack traces.
> You really might want to read the code I provided. Here's the reference
> again:
> The "header" referred to does indeed contain the exception raised. And
> the line numbers are included. Here's a typical output stanza:
Yes, but the dict is still keyed on the traceback alone, and only the
first header for a particular traceback is stored. If two different
exceptions occur at the same line of code and sharing the same
traceback, the second exception would be counted as a second
occurrence of the first, effectively squashing any reporting of the
second exception.
> Our requirements are to scan the logs of a production site and filter
> down the gobs and gobs of output (we produced 70 GB of log files
> yesterday) into something small enough that a human can see what the
> most common failures were. The tool I wrote does that.
> The rest of this conversation is just silly. It's turning into getting
> hit on the head lessons.
I agree. In early Python, tuples were more different from lists than they are today. They did not have any (public) methods. Today, they have .index and .count methods, which make little sense from the 'tuple is a record' viewpoint. The addition of those methods redefined tuples as read-only (and therefore hashable) sequences.
From the collections.abc doc
'''
Sequence | Sized, Iterable, Container |
__getitem__ __contains__, __iter__, __reversed__, index, and count
...
class collections.abc.Sequence
class collections.abc.MutableSequence
ABCs for read-only and mutable sequences.
'''
>>> from collections.abc import Sequence
>>> issubclass(tuple, Sequence)
True
On Mon, 19 Nov 2012 09:30:54 -0500, Roy Smith wrote:
> In article <50a9e5cf$0$21863$c3e8da3$76491...@news.astraweb.com>,
> Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote:
>> I see. It wasn't clear from your earlier description that the items had
>> been post-processed from collections of raw log lines to fixed records.
> Well, I did provide the code that does this.
You did? When? [goes back and looks]
Oh, so you did. Oops.
By the way, your news client seems to be mangling long URLs, by splitting them when they exceed the maximum line length. I didn't follow the link you gave because it was mangled, and then forgot it even existed. Sorry about that.
[...]
> You really might want to read the code I provided. Here's the reference
> again:
> The "header" referred to does indeed contain the exception raised. And
> the line numbers are included. Here's a typical output stanza:
[snip]
Ian Kelly has picked up on what I'm trying to say. You might collect the traceback in the "header", but it doesn't get used in the key, and each time you find a repeated stack trace, you toss away whatever header you just saw and keep the header you saw the first time.
In general, it is an unsafe assumption that the actual exception raised will be the same just because the stack trace is the same. So as I said, if you have two *distinct* failures occurring in the same function (not even necessarily on the same line), your code appears to treat them as the same error. That seems odd to me, but if you have a good reason for doing it that way, so be it.
On Mon, 19 Nov 2012 09:59:19 -0500, Roy Smith wrote:
> OK, I've just read back over the whole thread. I'm really struggling to
> understand what point you're trying to make. I started out by saying:
>> Use a list when you need an ordered collection which is mutable (i.e.
>> can be altered after being created). Use a tuple when you need an
>> immutable list (such as for a dictionary key).
> To which you obviously objected. So now you write:
>> I think a tuple is an immutable sequence of items, and a list is a
>> mutable sequence of items.
> So how is that different from what I said? Is this whole argument
> boiling down to your use of "immutable sequence" vs. my use of
> "immutable list"?
Sheesh, of course not. Give me some credit.
I gave some examples of when somebody might use lists, tuples, sets and dicts. Apparently I forgot a couple, and you responded with a sarcastic comment about the "One True Church Of Pythonic Orthodoxy And Theoretical Correctness" and gave a couple of additional examples.
Although I didn't come out and *explicitly* say "I agree" to your examples, I actually did, with one proviso: your example of using an "immutable list" as dict key. So I asked a question about that *specific* use-case:
[quote]
Under what sort of circumstances would somebody want to take a mutable
list of data, say a list of email addresses, freeze it into a known state,
and use that frozen state as a key in a dict? What would be the point?
Even if there was some meaningful reason to look up "this list of 12000
email addresses" as a single key, it is going to get out of sync with the
actual mutable list.
[end quote]
Your reply was to give your stack trace script as an example. That's a fine example as a use-case for a temporary list, and I've done similar things dozens, hundreds of times myself. As I said:
[quote]
Sure, I have built a collection of items as a list, because lists are
mutable, then frozen it into a tuple, and *thrown the list away*, then
used the tuple as a key. But that's not the same thing, the intent is
different. In my case, the data was never intended to be a list, it was
always intended to be a fixed record-like collection, the use of list was
as a temporary data structure used for construction. A bit like the idiom
of ''.join(some_list).
[end quote]
To me, this sounds *exactly* like your use-case: your data, stack traces, represent a little chunk of immutable data that you build up a line at a time using a temporary list first, just like I wrote. And I said so. There's no sign in either your code or your description that the stack traces get treated as mutable objects in any way once you have finished building them a line at a time. So your real world, practical, "in the trenches" example matches my experience: you build a *fixed data record* using a *temporary list*, throw the list away, and then never mutate that data record again.
So why are we disagreeing? Like many such discussions on the Internet, this one has rambled a bit, and I've misunderstood some of your code (sorry), and you seem to have misunderstood the question I am asking. Maybe my explanation was not clear enough, in which case, sorry again.
I'm asking about the case where one might want the key to remain mutable even after it is used as a key, but can't because Python won't let you. There's no sign that your stack trace example is such an example.
As I earlier said:
[quote]
But I can't think of any meaningful, non-contrived example where I might
want an actual mutable list of values as a dict key.
[end quote]
> OK, I've just read back over the whole thread. I'm really struggling to
> understand what point you're trying to make. I started out by saying:
> > Use a list when you need an ordered collection which is mutable (i.e.
> > can be altered after being created). Use a tuple when you need an
> > immutable list (such as for a dictionary key).
> To which you obviously objected. So now you write:
> > I think a tuple is an immutable sequence of items, and a list is a
> > mutable sequence of items.
> So how is that different from what I said? Is this whole argument
> boiling down to your use of "immutable sequence" vs. my use of
> "immutable list"?
'''
Roy:
> Use a list when you need an ordered collection which is mutable (i.e.
> can be altered after being created). Use a tuple when you need an
> immutable list (such as for a dictionary key).
Steven:
I keep hearing about this last one, but I wonder... who *actually* does this? I've created many, many lists over the years -- lists of names, lists of phone numbers, lists of directory search paths, all sorts of things. I've never needed to use one as a dictionary key.
'''
To me this is more of a question than an argument. Now moving
on to your specific example.
'''
def extract_stack(lines):
"in traceback_helper module "
header = lines[0]
stack = []
for line in lines:
m = frame_pattern.match(line)
if not m:
continue
frame = (m.group('path'), m.group('function'))
stack.append(frame)
# [Convert to tuple and return after finished building stack.]
return (header, stack)
[...]
def main(args):
crashes = {}
[...]
for line in open(log_file):
if does_not_look_like_a_stack_dump(line):
continue
lines = traceback_helper.unfold(line)
header, stack = traceback_helper.extract_stack(lines)
signature = tuple(stack)
if signature in crashes:
count, header = crashes[signature]
crashes[signature] = (count + 1, header)
else:
crashes[signature] = (1, header)
'''
Seems to me that Steven is suggesting that stack (after being built)
should converted to a tuple before being returned, because a "stack" for any unique exception should be unique and immutable. You do this
anyway; you just do it before putting it into a dictionary rather
than before returning it.
Same net effect (as long as you do not modify `stack` later), so no real argument.
~Ramit
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.
In article <50aac66c$0$29983$c3e8da3$54964...@news.astraweb.com>,
Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote:
> I'm asking about the case where one might want the key to remain mutable > even after it is used as a key, but can't because Python won't let you.
Ah. Now I see what you're getting at. Thank you.
Well, I will admit that it probably doesn't make sense to mutate an object after it's put into a dict (or at least mutate it in a way which changes it's hash value and/or whether it compares equal to the original object). If you did (assuming lists were allowed as keys):
l = [1, 2, 3]
d = {l: "spam"}
l.append(4)
print d[l]
I'm not sure what I would expect to print. It's not too hard to experiment, though. All you need do is:
class HashableList(list):
def __hash__(self):
return hash(tuple(self))
and python is then happy to let you use a list as a key. I just played around with this a bit off-line. I think I got the results I was expecting, but since I'm not sure what I was expecting, that's hard to say.
However, you didn't ask if it made sense to mutate an object after using it as a key. You asked if it made sense to let the object remain mutable after using it as a key. That's a harder question.
Let's say I had lots of of lists I wanted to use a dictionary keys. As it stands now, I have to convert them to tuples, which means copying all the data. For a lot of data, that's inefficient.
Wouldn't it be nice (or at least, more efficient) if I could just use the original lists as keys directly, without the extra copy? I would have to understand that even though they are mutable, interesting (and perhaps, unwanted) things if I actually mutated them. But, we're all consenting adults here. If I'm willing to accept responsibility for the consequences of my actions in return for the efficiency gain, why shouldn't I be allowed to?
I guess the answer is, that I am allowed to. I just need to do the HashableList deal, shown above (no broken URL required to read the code).
----- Original Message ----- > Use a set when you want to represent a collection of items and the > order > is not important:
An important feature of sets is that their items are unique. set(list(...)) is a good shortcut to remove duplicate in a list.
JM
-- IMPORTANT NOTICE:
The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.