When you've been using a programming language for a long time, you like to think that syntax-wise, it has no more secrets left for you.
Today I was proven wrong and found out about Python's extended slice assignment, which is present since Python 2.3.5.
While this code does more or less the same thing as my sieve code, I was puzzled about line 7. This syntax was new to me.
I knew about the step argument for slices, making things like getting all even numbers from a range as easy as:
What I didn't know, is that you can assign an equal-length sequence to the slice and have it replace those values, given that the sequence is mutable (eg. a list) like this:
Now that's a useful trick to know if you didn't already!
One of the reasons the above mentioned sieve was so much faster than mine, is that by clever use of the extended slice assignment syntax, the crossing-off of multiples is done with one assignment instead of many in a loop.blog comments powered by Disqus