473,695 Members | 2,043 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

slicing, mapping types, ellipsis etc.

Fellow Pythonists;

I am totally puzzled on the use of slicing on mapping types and
especially unsure on use of the Ellipsis... and slicing syntax that
has two or more groups seperated by comma.

I am referring to (from the manual);

Slice objects
Slice objects are used to represent slices when extended
slice syntax is used. This is a slice using two colons, or multiple
slices or ellipses separated by commas, e.g., a[i:j:step], a[i:j,
k:l], or a[..., i:j]. They are also created by the built-in slice()
function.

A quick example on how this is used and/or pointer to more reading is
greatly appreciated.

Thanks
--
-------------------------------------------------------------------------------
Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant
305 321-1144 (mobile http://www.JerrySievers.com/
Jul 18 '05 #1
9 2470
I'm going to assume the following is self-explanatory - type the commands
in yourself.

'>>> a = 'hello my name is caleb'
'>>> b = a.split()
'>>> b
['hello', 'my', 'name', 'is', 'caleb']
'>>> b[0]
'hello'
'>>> b[1]
'my'
'>>> b[0:1]
['hello']
'>>> b[0:2]
['hello', 'my']
'>>> b[-1]
'caleb'
'>>> b[:-2]
['hello', 'my', 'name']
'>>> b[2:-2]
['name']
'>>>

thx
Caleb

On 29 Nov 2004 15:49:30 -0500, Jerry Sievers <je***@jerrysie vers.com>
wrote:

Slice objects
Slice objects are used to represent slices when
extended
slice syntax is used. This is a slice using two colons, or
multiple
slices or ellipses separated by commas, e.g., a[i:j:step],
a[i:j,
k:l], or a[..., i:j]. They are also created by the built-in
slice()
function.

A quick example on how this is used and/or pointer to more reading is
greatly appreciated.

Thanks


Jul 18 '05 #2
"Caleb Hattingh" <ca****@telkoms a.net> writes:
I'm going to assume the following is self-explanatory - type the commands
in yourself.


[snip]

Yes, it certainly is self-explanatory. And, I appreciate your
response.

However, my question pertains to advanced use of the slicing features
which I have found to be not totally explained in the docs.

The use of [start:stop:step] on sequence types is NOT unclear to me at
all.

I'd like to know;

1. what the Ellipsis object or ... syntax is used for
2. what a slice [..., j:k:l] does
3. how slices are applied to object of mapping types

Thank you

--
-------------------------------------------------------------------------------
Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant
305 321-1144 (mobile http://www.JerrySievers.com/

--
-------------------------------------------------------------------------------
Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant
305 321-1144 (mobile http://www.JerrySievers.com/
Jul 18 '05 #3
Jerry Sievers wrote:
1. what the Ellipsis object or ... syntax is used for
2. what a slice [..., j:k:l] does
My understanding is that the Ellipsis object is intended primarily for
Numeric/numarray use. Take a look at:

http://stsdas.stsci.edu/numarray/num...ml/node26.html
3. how slices are applied to object of mapping types


The short answer is that they aren't. Slices aren't hashable, so dicts
can't handle them:
d = {}
d = {1:'a', 2:'b'}
d[1:2] Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: unhashable type hash(slice(1, 2)) Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: unhashable type

You can, however handle them if you write your own mapping type:
class M(object): .... def __getitem__(sel f, x):
.... if isinstance(x, slice):
.... return x.start, x.stop, x.step
.... else:
.... return x
....
m = M()
m[1] 1 m[1:2]

(1, 2, None)

Hope this helps!

Steve
Jul 18 '05 #4
Jerry Sievers wrote:
I'd like to know;
1. what the Ellipsis object or ... syntax is used for Use the Numeric (or numarray) package to really see these in use.
Otherwise, you mostly get to implement it yourself.
2. what a slice [..., j:k:l] does Again, see numeric. Essentially, select parts of a matrix (or higher
dimensional array) based on a stride in the last dimension.
3. how slices are applied to object of mapping types

One way to investigate this interactively:

class CheckOut(object ):
def __init__(self, name=None):
self.name = name or str(self)
def __getitem__(sel f, *args, **kwargs):
print '%s._gi_(*%r, **%r):' % (self.name, args, kwargs),
return input()
c = CheckOut('a')
b = c[1, ...] c.gi(*(1, Ellipsis), **{}): self.name * 7 b

'aaaaaaa'

--Scott David Daniels
Sc***********@A cm.Org
Jul 18 '05 #5
On 29 Nov 2004 16:45:52 -0500, Jerry Sievers <je***@jerrysie vers.com> wrote:
"Caleb Hattingh" <ca****@telkoms a.net> writes:
I'm going to assume the following is self-explanatory - type the commands
in yourself.


[snip]

Yes, it certainly is self-explanatory. And, I appreciate your
response.

However, my question pertains to advanced use of the slicing features
which I have found to be not totally explained in the docs.

The use of [start:stop:step] on sequence types is NOT unclear to me at
all.

I'd like to know;

1. what the Ellipsis object or ... syntax is used for
2. what a slice [..., j:k:l] does
3. how slices are applied to object of mapping types
class C(object): ... def __getitem__(sel f, i): print i; return None
... c=C()
c[1] 1 c[1:2] slice(1, 2, None) c[1:2:3] slice(1, 2, 3) c[:2:3] slice(None, 2, 3) c[::3] slice(None, None, 3) c[::] slice(None, None, None) c[1,::] (1, slice(None, None, None)) c[1,...,::] (1, Ellipsis, slice(None, None, None)) c[1, 2, ..., 3:4] (1, 2, Ellipsis, slice(3, 4, None)) c[...] Ellipsis

An object implementing __getitem__ (and/or __setitem__) will be passed arguments
as above and is free to use them in any way that makes sense to it's author.
Making sense to the users of the author's software is another thing ;-)

AFAIK Ellipsis is just a special builtin object that can be used as a handy
standard place holder in the get/setitem context. But any other builtin
could be passed also, e.g.,
c[1,2,abs,3] (1, 2, <built-in function abs>, 3)

so AFAIK it's just that an Ellipsis reference is generated when you use ... in the
getitem context. The compiler generates a reference to the built-in constant, so
you can make a test for it for your object's logic, e.g.
class C(object): ... def __getitem__(sel f, i):
... if i is Ellipsis or isinstance(i, tuple) and Ellipsis in i:
... print 'got ... in the index arg %r'%(i,)
... else:
... print 'did not get ... in the index arg %r'%(i,)
... c=C()
c[1,2] did not get ... in the index arg (1, 2) c[::] did not get ... in the index arg slice(None, None, None) c[::, ...] got ... in the index arg (slice(None, None, None), Ellipsis) c[...] got ... in the index arg Ellipsis c[Ellipsis] got ... in the index arg Ellipsis

But interestingly, compare the appearance of Ellipsis in the disassembly
of foo and bar (LOAD_GLOBAL vs LOAD_CONST). The global you can shadow or
rebind, but the const is apparently known by the compiler, and it is arranged
that they both refer to the same object by default, so the 'is' test succeeds.
class C(object): ... def __getitem__(sel f, i): return i
... def foo(self): return self[...]
... def bar(self): return self.foo() is Ellipsis
... c= C()
c[...] is Ellipsis True c.foo() is Ellipsis True c.bar() True import dis
dis.dis(C)

Disassembly of __getitem__:
2 0 LOAD_FAST 1 (i)
3 RETURN_VALUE

Disassembly of bar:
4 0 LOAD_FAST 0 (self)
3 LOAD_ATTR 1 (foo)
6 CALL_FUNCTION 0
9 LOAD_GLOBAL 2 (Ellipsis)
12 COMPARE_OP 8 (is)
15 RETURN_VALUE

Disassembly of foo:
3 0 LOAD_FAST 0 (self)
3 LOAD_CONST 1 (Ellipsis)
6 BINARY_SUBSCR
7 RETURN_VALUE

HTH

Regards,
Bengt Richter
Jul 18 '05 #6
Jerry Sievers wrote:
Fellow Pythonists;

I am totally puzzled on the use of slicing on mapping types and
It's generally not supported (since slices are designed to work with the
numerical indices of a sequence, not the arbitrary keys of a mapping).

The results of d.keys(), d.values() & d.items() can all be sliced like any other
sequence, though.
especially unsure on use of the Ellipsis... and slicing syntax that
has two or more groups seperated by comma.


Others have explained these - one point that may not have been entirely clear is
that none of the classes in the standard library make use of these (although the
point may have been implied by the references to PyNumeric as the place to look
for more exact documentation. Python's own documentation of the slice() builtins
makes reference to Numeric!).

Cheers,
Nick.

Jul 18 '05 #7
Nick Coghlan wrote:
Jerry Sievers wrote:
Fellow Pythonists;

I am totally puzzled on the use of slicing on mapping types and

It's generally not supported (since slices are designed to work with the
numerical indices of a sequence, not the arbitrary keys of a mapping).


Section 5.3.3 of the Language Reference seems to say that with extended
slicing, the slice elements are used to create a key that indexes a
mapping. "The semantics for an extended slicing are as follows. The
primary must evaluate to a mapping object, and it is indexed with a key
that is constructed from the slice list, as follows."

From my understanding of this thread so far, extended slicing is used
as a form of indexing in Numeric. Are Numeric arrays considered
mappings? Or is this paragraph in 5.3.3 off the mark?

Maybe instead of referring to mappings it should say "The primary must
implement __getitem__(), which is called with a value that is
constructed from the slice list, as follows."

Kent
Jul 18 '05 #8
Kent Johnson wrote:
Maybe instead of referring to mappings it should say "The primary must
implement __getitem__(), which is called with a value that is
constructed from the slice list, as follows."


In the section you mention, 'mapping' is equivalent to 'has __getitem__
defined', and I'd be surprised if it's an isolated usage. Python actually has
trouble distinguishing between sequences and mappings, as anyone who as tried to
use the 'isMapping' API would know (the isMapping API uses much the same
definition as the reference manual does - so all sequences show up as mappings,
as they map indices and slices to objects).

Section 3 of the reference manual is actually more use for anyone developing
custom types that override special methods. E.g. proper handling of slice
objects is described here under container emulation:
http://www.python.org/dev/doc/devel/...nce-types.html

Regards,
Nick.

Jul 18 '05 #9
Nick Coghlan wrote:
Kent Johnson wrote:
Maybe instead of referring to mappings it should say "The primary must
implement __getitem__(), which is called with a value that is
constructed from the slice list, as follows."

In the section you mention, 'mapping' is equivalent to 'has __getitem__
defined', and I'd be surprised if it's an isolated usage. Python
actually has trouble distinguishing between sequences and mappings, as
anyone who as tried to use the 'isMapping' API would know (the isMapping
API uses much the same definition as the reference manual does - so all
sequences show up as mappings, as they map indices and slices to objects).

Section 3 of the reference manual is actually more use for anyone
developing custom types that override special methods. E.g. proper
handling of slice objects is described here under container emulation:
http://www.python.org/dev/doc/devel/...nce-types.html


I understand that the distinction between sequences and mappings is
fuzzy, as both use __getitem__() for access. But the usage of 'mapping'
in 5.3.3 is inconsistent with the section you refer to. That page says
"It is also recommended that mappings provide the methods keys(),
values(), items(), has_key(), get(), clear(), setdefault(), iterkeys(),
itervalues(), iteritems(), pop(), popitem(), copy(), and update()
behaving similar to those for Python's standard dictionary objects."

and under __getitem__(): "For *sequence* types, the accepted keys should
be integers and slice objects."

I just think 5.3.3 is unnecessarily opaque. Particularly since the only
built-in mapping (dict) doesn't even accept simple slices as indices.

Kent

Regards,
Nick.

Jul 18 '05 #10

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

Similar topics

3
2054
by: Bryan Olson | last post by:
I recently wrote a module supporting value-shared slicing. I don't know if this functionality already existed somewhere, but I think it's useful enough that other Pythoners might want it, so here it is. Also, my recent notes on Python warts with respect to negative indexes were based on problems I encoutered debugging this module, so I'm posting it partially as a concrete example of what I was talking about.
17
16550
by: Jon Slaughter | last post by:
I'm having a little trouble understanding what the slicing problem is. In B.S.'s C++ PL3rdEd he says "Becayse the Employee copy functions do not know anything about Managers, only the Employee part of Manager is copied. ".... and gives the code above as .....
17
3566
by: baibaichen | last post by:
i have written some code to verify how to disable slicing copy according C++ Gotchas item 30 the follow is my class hierarchy, and note that B is abstract class!! class B { public: explicit B(INT32 i =0):i_(i){} virtual ~B(){}
22
2357
by: bearophileHUGS | last post by:
>From this interesting blog entry by Lawrence Oluyede: http://www.oluyede.org/blog/2006/07/05/europython-day-2/ and the Py3.0 PEPs, I think the people working on Py3.0 are doing a good job, I am not expert enough (so I don't post this on the Py3.0 mailing list), but I agree with most of the things they are agreeing to. Few notes: - input() vanishes and raw_input() becomes sys.stdin.readline(). I think a child that is learning to program...
14
2302
by: Lane Straatman | last post by:
I would like to write a 'struct'. I have a library that is all but completely inappropriate for this task. So I'm looking for C code that fills in the gaps between: #undef whateverkeithsaysfor99compliance #define whateverkeithsays for99compliance int main(void { struct foo
2
1855
by: Alona | last post by:
Hello, Does W3C defines a standard for mapping XML types to C/C++ built-in types and vise versa? Thank you, Alona
1
3469
by: Bart Simpson | last post by:
Can anyone explain the concept of "slicing" with respect to the "virtual constructor" idiom as explain at parashift ? From parashift: class Shape { public: virtual ~Shape() { } // A virtual destructor
1
2122
by: Rodney Maxwell | last post by:
The following are apparently legal Python syntactically: L L But they don't seem to work on lists: Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list indices must be integers Traceback (most recent call last): File "<stdin>", line 1, in <module>
5
2571
by: alan | last post by:
Hello world, I'm wondering if it's possible to implement some sort of class/object that can perform mapping from class types to strings? I will know the class type at compile time, like so: const char *s = string_mapper<thetype>(); However I do not know the string to be associated with the type at compile time, and will need a way to set up the mapping, to be created at run time, possibly like so: void foo(char*...
0
8630
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9115
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8845
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
7660
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
6491
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
4579
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3003
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
2272
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1976
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.