473,804 Members | 3,247 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

slice notation as values?

Now slices are objects in python, I was wondering if slice
notation will be usable outside subscribtion in the future.

Will it ever be possible to write things like:

a = 4:9
for key, value in tree.items('alf a.': 'beta.'):

--
Antoon Pardon
Dec 9 '05
23 2344
Op 2005-12-11, Bengt Richter schreef <bo**@oz.net> :
On 10 Dec 2005 12:07:12 -0800, "Devan L" <de****@gmail.c om> wrote:

Antoon Pardon wrote:
On 2005-12-10, Duncan Booth <du**********@i nvalid.invalid> wrote:

[snip]
>> I also think that other functions could benefit. For instance suppose
>> you want to iterate over every second element in a list. Sure you
>> can use an extended slice or use some kind of while. But why not
>> extend enumerate to include an optional slice parameter, so you could
>> do it as follows:
>>
>> for el in enumerate(lst,: :2)
>
> 'Why not'? Because it makes for a more complicated interface for something
> you can already do quite easily.

Do you think so? This IMO should provide (0,lst[0]), (2,lst[2]),
(4,lst[4]) ...

I haven't found a way to do this easily. Except for something like:

start = 0:
while start < len(lst):
yield start, lst[start]
start += 2

But if you accept this, then there was no need for enumerate in the
first place. So eager to learn something new, how do you do this
quite easily?

> lst = ['ham','eggs','b acon','spam','f oo','bar','baz']
> list(enumerate( lst))[::2]

[(0, 'ham'), (2, 'bacon'), (4, 'foo'), (6, 'baz')]

No changes to the language necessary.

Or, without creating the full list intermediately,
lst = ['ham','eggs','b acon','spam','f oo','bar','baz']
import itertools
list(itertools. islice(enumerat e(lst), 0, None, 2))

[(0, 'ham'), (2, 'bacon'), (4, 'foo'), (6, 'baz')]


As far as I understand use of this idiom can turn an O(n)
algorithm into an O(n^2) algorithm.

Suppose I have a list with 10 000 elements and I want
the sum of the first 100, the sum of the second 100 ...

One way to do that would be:

for i in xrange(0,10000, 100):
sum(itertools.i slice(lst, i, i+100))

But itertools.islic e would each time start from the begining
of the list and iterate over i elements before giving 100
elements to sum. Which would make this implementation O(n^2)
instead of O(n).

--
Antoon Pardon
Dec 12 '05 #21

Antoon Pardon wrote:
Suppose I have a list with 10 000 elements and I want
the sum of the first 100, the sum of the second 100 ...

One way to do that would be:

for i in xrange(0,10000, 100):
sum(itertools.i slice(lst, i, i+100))

But itertools.islic e would each time start from the begining
of the list and iterate over i elements before giving 100
elements to sum. Which would make this implementation O(n^2)
instead of O(n).

Can you use iter for this situation ?

a=iter(lst)
for i in xrange(0,10000, 100):
sum(itertools.i slice(a,100))

Dec 12 '05 #22
On 12 Dec 2005 08:34:37 GMT, Antoon Pardon <ap*****@forel. vub.ac.be> wrote:
Op 2005-12-10, Devan L schreef <de****@gmail.c om>:

Antoon Pardon wrote:
On 2005-12-10, Duncan Booth <du**********@i nvalid.invalid> wrote:

[snip]
>> I also think that other functions could benefit. For instance suppose
>> you want to iterate over every second element in a list. Sure you
>> can use an extended slice or use some kind of while. But why not
>> extend enumerate to include an optional slice parameter, so you could
>> do it as follows:
>>
>> for el in enumerate(lst,: :2)
If you are willing to use square brackets, you can spell it
for el in enoomerate[lst, ::2]: print el,
(see below ;-)
>
> 'Why not'? Because it makes for a more complicated interface for something
> you can already do quite easily.

Do you think so? This IMO should provide (0,lst[0]), (2,lst[2]),
(4,lst[4]) ...

I haven't found a way to do this easily. Except for something like:

start = 0:
while start < len(lst):
yield start, lst[start]
start += 2

But if you accept this, then there was no need for enumerate in the
first place. So eager to learn something new, how do you do this
quite easily?

> lst = ['ham','eggs','b acon','spam','f oo','bar','baz']
> list(enumerate( lst))[::2]

[(0, 'ham'), (2, 'bacon'), (4, 'foo'), (6, 'baz')]


It is not about what is needed, but about convenience.

Now let me see, in order to just iterate over the even elements
of a list with the index of the element, you turned an iterator
into a list, which you use to create an other list which you
will finaly iterate over.

If this is the proposed answer, I wonder why iterators were introduced
in the first place. I thought iterator were went to avoid the need
to construct and copy list when all you want is iterate and when
I ask how to get a specific iterator you come with a construct that
makes rather heavily use of list constructions.

Just for you ;-)
import itertools
class enoomerate(obje ct): ... def __getitem__(sel f, seq):
... if isinstance(seq, tuple):
... seq, slc = seq
... else:
... slc = slice(None)
... if not isinstance(slc, slice): slc = slice(None, slc)
... return itertools.islic e(enumerate(seq ), slc.start or 0, slc.stop, slc.step or 1)
... enoomerate = enoomerate()

import string
lst = list(string.asc ii_lowercase) # legit list, though could use the string
for el in enoomerate[lst, ::2]: print el, ...
(0, 'a') (2, 'c') (4, 'e') (6, 'g') (8, 'i') (10, 'k') (12, 'm') (14, 'o') (16, 'q') (18, 's') (
20, 'u') (22, 'w') (24, 'y') for el in enoomerate[lst, 3::3]: print el, ...
(3, 'd') (6, 'g') (9, 'j') (12, 'm') (15, 'p') (18, 's') (21, 'v') (24, 'y') for el in enoomerate[lst, 3]: print el, ...
(0, 'a') (1, 'b') (2, 'c') for el in enoomerate[lst, 3:6]: print el, ...
(3, 'd') (4, 'e') (5, 'f') for el in enoomerate[lst, 3:6:2]: print el,

...
(3, 'd') (5, 'f')

Regards,
Bengt Richter
Dec 12 '05 #23
Op 2005-12-12, Bengt Richter schreef <bo**@oz.net> :
On 12 Dec 2005 08:34:37 GMT, Antoon Pardon <ap*****@forel. vub.ac.be> wrote:
Op 2005-12-10, Devan L schreef <de****@gmail.c om>:

Antoon Pardon wrote:
On 2005-12-10, Duncan Booth <du**********@i nvalid.invalid> wrote:
[snip]
>> I also think that other functions could benefit. For instance suppose
>> you want to iterate over every second element in a list. Sure you
>> can use an extended slice or use some kind of while. But why not
>> extend enumerate to include an optional slice parameter, so you could
>> do it as follows:
>>
>> for el in enumerate(lst,: :2)
If you are willing to use square brackets, you can spell it
Hmm, I have to think about that.
for el in enoomerate[lst, ::2]: print el,
(see below ;-)
[ ... ]

Just for you ;-)


Thank you.
import itertools
class enoomerate(obje ct): ... def __getitem__(sel f, seq):
... if isinstance(seq, tuple):
... seq, slc = seq
... else:
... slc = slice(None)
... if not isinstance(slc, slice): slc = slice(None, slc)
... return itertools.islic e(enumerate(seq ), slc.start or 0, slc.stop, slc.step or 1)
... enoomerate = enoomerate()

import string
lst = list(string.asc ii_lowercase) # legit list, though could use the string
for el in enoomerate[lst, ::2]: print el,


I am wondering a bit. Could this be turned into a decorator?

I don't have much experience with decorators, so I'll have to
think this through for a wgile. The idea would be a class
to be used as decorator that would turn a function returning
an iterator in a slicable iterator. Something like the following
maybe:

class SliceIterator(o bject):

def __init__(self,f unc):
self.func = func

def __getitem__(sel f, args):
if isinstance(args , tuple)
return self.func(*args )
else:
return self.func(args)

def __iter__(self):
return self.func(slice (None, None, None))

I could then write something like:

@SliceIterator
def srange(sl):
v = sl.stop
while v < sl.start:
yield v
v += sl.step
And use it as:

for i in srange[23:67:3]:
...

Hmm, I have to play with this a bit. Thanks for the idea.

--
Antoon Pardon
Dec 12 '05 #24

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
2495
by: Roberto A. F. De Almeida | last post by:
I found that when using negative indices, the slice object passed to __getitem__ depends on the number of slices. An example to clarify: class a: def __getitem__(self, index): return index >>> b = a() >>> print b Traceback (most recent call last):
3
2360
by: Thomas Covello | last post by:
Why does the following code give this error: >>> TypeError: sequence index must be integer
4
2936
by: F. Da Costa | last post by:
Hi, I was wondering whether someone could enlighten me as to the reason why the slice does not work in IE when the arr is passed in properly. Checked the values in the srcArr and they are correct so no problems there. Gecko works as expected. Prior to entering the function I can slice the array being entered so I wouldn't expect an "Unexpected call to method or property access" (in IE 6). I guess its something silly but as of yet i'm...
108
6476
by: Bryan Olson | last post by:
The Python slice type has one method 'indices', and reportedly: This method takes a single integer argument /length/ and computes information about the extended slice that the slice object would describe if applied to a sequence of length items. It returns a tuple of three integers; respectively these are the /start/ and /stop/ indices and the /step/ or stride length of the slice. Missing or out-of-bounds indices are handled in a manner...
40
2624
by: Ron Adam | last post by:
After considering several alternatives and trying out a few ideas with a modified list object Bengt Richter posted, (Thank You), I think I've found a way to make slice operation (especially far end indexing) symmetrical and more consistent. So to find out if this is indeed a possibility, it would be nice to get a few opinions at this point. So blast away... or hopefully tell me what you like about it instead. ;-) (Any suggestions or...
19
2913
by: George Sakkis | last post by:
It would be useful if list.sort() accepted two more optional parameters, start and stop, so that you can sort a slice in place. In other words, x = range(1000000) x.sort(start=3, stop=-1) would be equivalent to x = sorted(x)
2
7256
by: smichr | last post by:
It seems to me that the indices() method for slices is could be improved. Right now it gives back concrete indices for a range of length n. That is, it does not return any None values. Using an example from clpy about this the indices for a 'None, None, -2' slice for a range of length 10 are given as '9, -1, -2'. The problem is that these concrete values cannot be fed back into a slice so that a slice will extract the same elements that...
0
9588
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10340
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10327
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9161
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7625
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6857
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4302
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3828
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.