[Tutor] Python vs. C

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Jan 7 13:56:08 EST 2004

> And my friend left me to wonder about this: why is it faster?

Hi Marilyn,

Python is doing a lot more for you then meets the eye.  A program like

l = [0 * 4]
for i in range(20):
    l[i] = i

is obviously buggy, but at least Python will give a good error message:

Traceback (most recent call last):
  File "<stdin>", line 2, in ?
IndexError: list assignment index out of range

That is, on every list assignment, Python is actively checking to see if
the index is in the range of our list.  If it isn't, it throws an
exception.  This sort of bug can be caught gracefully at least, and at no
point has Python lost control: it is voluntarily exiting, with the full
knowledge that an IndexError has occurred.

C provides no such guarantees, and the following C program:

int main() {
    int l[4];
    int i;
    for (i = 0; i < 20; i++) {
        l[i] = i;
    return 0;

does no "range checking", and will break terribly with a very ugly error

[dyoo at tesuque dyoo]$ ./a.out
Segmentation fault (core dumped)

That error message that you're seeing there is not coming from our program
either.  Rather, it's coming from the operating system itself --- the OS
sees that the program is doing something hideous with memory, and kills
the program in self defense.  *grin*

So compilation is sort of a red herring here: Python is slower because
it's simply doing more for you.  If a Python program were compiled into
machine code, it would still be slow because it's doing more work at

Not that this extra work is always a bad thing!  Many of the computer
"security flaws"  that you have been hearing in the news lately is
entirely due to C's hands-off approach to memory and range checking.  If
many of the programs that are currently in use had been written in a more
modern language, those sort of attacks would have been obsolete a long
time ago.  C sacrifies safety for speed.

Talk to you later!

More information about the Tutor mailing list