Slices time complexity

Chris Angelico rosuav at gmail.com
Tue May 19 13:19:56 EDT 2015


On Wed, May 20, 2015 at 3:07 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> True confession time: I've been using Python for over 15 years. For at least
> 12 of those years, I've found myself feeling guilty every time I write a
> loop like "for x in seq[1:]" to skip the first element, because I'm worried
> about copying a huge list. Every single time I think "I really ought to
> write a list view." And then I think about the effort involved (minor)
> versus the benefit (even smaller) and I think "screw it, I'll just make a
> copy".
>
> And in 12 years, this lazy "put off until tomorrow" attitude to list views
> has failed me exactly *zero* times. I won't say You're Not Gonna Need It,
> but I will say *I've* Never Needed It Yet.

I can't think of many times when I've needed to do this on a large
list - usually it's either a generic iterable handler (so it has to
call iter() and then next(), and then iterate over what's left), or
it's sys.argv. I literally cannot think of any other situation where
I've iterated over seq[1:] than sys.argv. And if you're passing a
million args to a program, frankly, you have more to worry about than
the cost of trimming off the self-name to iterate over the rest of the
args. Worries like, yaknow, actually doing some work with whatever was
passed in as args, which is likely to dwarf the list slicing time.

ChrisA



More information about the Python-list mailing list