Arithmetic sequences in Python
Antoon Pardon
apardon at forel.vub.ac.be
Tue Jan 17 04:11:43 EST 2006
Op 2006-01-16, Alex Martelli schreef <aleax at mail.comcast.net>:
> Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote:
>
>> Steven D'Aprano <steve at REMOVETHIScyber.com.au> writes:
>> > For finite sequences, your proposal adds nothing new to existing
>> > solutions like range and xrange.
>>
>> Oh come on, [5,4,..0] is much easier to read than range(5,-1,-1).
>
> But not easier than reversed(range(6)) [[the 5 in one of the two
> expressions in your sentence has to be an offbyone;-)]]
Why don't we give slices more functionality and use them.
These are a number of ideas I had. (These are python3k ideas)
1) Make slices iterables. (No more need for (x)range)
2) Use a bottom and stop variable as default for the start and
stop attribute. top would be a value that is greater than
any other value, bottom would be a value smaller than any
other value.
3) Allow slice notation to be used anywhere a value can be
used.
4) Provide a number of extra operators on slices.
__neg__ (reverses the slice)
__and__ gives the intersection of two slices
__or__ gives the union of two slices
5) Provide sequences with a range (or slice) method.
This would provide an iterator that iterates over
the indexes of the sequences. A slice could be
provided
for i in xrange(6):
would then become
for i in (0:6):
for a reversed sequence
for i in reversed(xrange(6)):
would become
for i in - (0:6):
for i, el in enumerate(sequence):
would become
for i in sequence.range():
el = sequence[i]
But the advantage is that this would still work when
someone subclasses a list so that it start index
is an other number but 0.
If you only wanted every other index one could do
the following
for i in sequence.range(::2):
which would be equivallent to
for i in sequence.range() & (::2):
--
Antoon Pardon
More information about the Python-list
mailing list