Slices time complexity

Mario Figueiredo marfig at gmail.com
Wed May 20 15:51:14 EDT 2015


On Wed, 20 May 2015 03:07:03 +1000, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:

>Yes, a slice can be expensive, if you have (say) a ten billion element list,
>and take a slice list[1:].

Since nothing seems to surprise you and you seem so adamant on calling
anyone being surprised by it, maybe I will surprise you if you
actually run the code I posted on the OP and witness for yourself that
even on a 50 element list will take 3 seconds to execute on an intel
i5.

>But, really... if you're serious about dealing with huge arrays of data, you
>want something like numpy, not Python lists.

You don't need huge. On any algorithm where slices are being used you
will have to account for the linear complexity. You seem to be
dismissive of this fact, but it can have tremendous performance
implications, since it can turn a linear algorithm into a quadratic
one just like that.

Certainly there are alternatives and iterating through the list is a
much better method. There's no arguing against that. But if you are
paying attention to how Python is being taught, [1:] is a little
everywhere on the web announced as a cool trick showcasing Python
strengths. Well, it turns out it is actually a bad practice
performance-wise under many cases and the alternatives should be the
ones being showcased.

> So *in practice* the lack of views for lists is a minor nuisance, if that.

Your opinion was noted.

> Having list slices return copies rather than views avoids more problems than it causes.

Well, I personally wouldn't want to see slices do anything other than
what they are doing now. I think that is the point. Backwards
compatibilioty being just one of the problems.

But no one is arguing for that. Instead, it was said that it would be
interesting if Python offered views.

>On the other hand, if Python implementations would implement slices with
>copy-on-write, that would give us the best of both worlds!

You are a confusing person. You after all agree with what is being
said, but spend all your time talking against it.



More information about the Python-list mailing list