473,544 Members | 1,966 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Jumping around when assigning elements

Python Newbie here. This is my first time learning object-oriented
programming and trying to break out of the usual Korn/Perl/PHP style
of programming. Having some difficulty understand some items.

For lists, I understand this:
C=["need","some"," help"]
print C[1]
some

But I can't seem to do this:
C[3]="here"

I know about C.append("here" ) but this brings me to my question...

Is there anyway to assign to an element that wasn't defined in the
beginning? Like if I wanted element 5 assigned but not element 4
without using "" or None?

I'm currently re-writing a Perl script into Python and with Perl I was
free to assign any element in the array without having to fill in the
previous elements. I can't seem to do that in Python...unless I'm
doing it wrong.

Thanks
--Matt
Jul 18 '05 #1
10 1801
Matthew Sims wrote in message
<1e************ **************@ posting.google. com>...
Python Newbie here. This is my first time learning object-oriented
programming and trying to break out of the usual Korn/Perl/PHP style
of programming. Having some difficulty understand some items.

For lists, I understand this:
C=["need","some"," help"]
print C[1]
some

But I can't seem to do this:
C[3]="here"

I know about C.append("here" ) but this brings me to my question...

Is there anyway to assign to an element that wasn't defined in the
beginning? Like if I wanted element 5 assigned but not element 4
without using "" or None?
I assume you tried 'insert'?
C=["need","some"," help"]
C.insert(10, 'here')
C

['need', 'some', 'help', 'here']

Ah, well that didn't work. Python has no (builtin) way to do what you want.
The reason isn't technical, but that the list needs *something* in that
intervening space, and Python isn't about to make rash presumptions about
what you want there ("explicit is better than implicit"). In choosing
between two behaviors for inserting to an index beyond the end of a list,
appending was deemed less surprising, less violent, and less likely to
introduce mysterious bugs than filling in the intermediate elements with
who-knows-what.

I can't even think of why one would want lists to have that sort of
behavior. It seems to me that if we're assigning to arbitrary elements and
we want the list to grow with it, that we should be using a different data
structure, like a dictionary with integer keys. The index of a list
generally has no semantic correlation to the data contained therein--it just
specifies order, and the data doesn't care about its own index. If we want
a semantic correlation, we make that correlation explicit by a dictionary's
key-value pair.

If you want to do this sort of thing (implicit assignment to intermediate
elements in list insertions), write a function to do it, or subclass list.
You can even modify the slice behavior itself (if you go the subclass
route), so that C[3] will silently act like perl instead of Python, but this
is *quite* unPythonic. (Other Python people reading your code will be
confused.)

If this sort of answer surprises you (coming from perl, it might...), do an
"import this" at an interactive prompt and read. :)
I'm currently re-writing a Perl script into Python and with Perl I was
free to assign any element in the array without having to fill in the
previous elements. I can't seem to do that in Python...unless I'm
doing it wrong.


Again, in general, Python has *no* implicit
assignments/declarations/modifications/etc. If you don't *explicitly* ask a
list to fill in its intermediate elements, Python won't do it. This is a
conscious design decision, and a great part of what makes Python Python.
For at least two senses of "great", IMO.

I could never learn perl (despite many attempts), so I ask, what does perl
do to the intermediate elements? Is a perl array more like a dictionary
with implicit integer keys (so intermediate keys simply don't exist), or
does it fill in the intermediate elements with 0 or something like that? In
what perl idioms is this behavior useful? (I still mean to learn perl one
of these days, for shell scripting.)
--
Francis Avila

Jul 18 '05 #2
Francis Avila wrote:
Matthew Sims wrote in message
of programming. Having some difficulty understand some items.

I'm currently re-writing a Perl script into Python and with Perl I
was free to assign any element in the array without having to fill
in the previous elements. I can't seem to do that in Python...unless
I'm doing it wrong.
Again, in general, Python has *no* implicit
assignments/declarations/modifications/etc. If you don't
*explicitly* ask a list to fill in its intermediate elements, Python
won't do it. This is a conscious design decision, and a great part
of what makes Python Python. For at least two senses of "great", IMO.


As were stated here many times it's not a good idea to mechanicaly
translate perl to python, they are quite different in approaches
despite similar syntax and capabilities.
Better understand initial script logic and write python from scratch.
In your case it might be list, dictionary or even none of them, so
it's highly dependent on the task at hand.
I could never learn perl (despite many attempts), so I ask, what does
perl do to the intermediate elements? Is a perl array more like a
dictionary with implicit integer keys (so intermediate keys simply
don't exist), or does it fill in the intermediate elements with 0 or
something like that? In what perl idioms is this behavior useful?
(I still mean to learn perl one of these days, for shell scripting.)


perl doesn't assigns them, they are 'undef', so it's more like python's dict

Mike


Jul 18 '05 #3
Matthew Sims wrote:
Is there anyway to assign to an element that wasn't defined in the
beginning? Like if I wanted element 5 assigned but not element 4
without using "" or None?
You can write your own class:

class GrowingList(lis t):
def __init__(self, seq, default=None):
list.__init__(s elf, seq)
self.default = default
def __setitem__(sel f, index, value):
if index >= len(self):
self.extend([self.default]*(index - len(self)))
self.append(val ue)
else:
list.__setitem_ _(self, index, value)
g = GrowingList(["alpha", "beta", "gamma"])
g[7] = "omega"
print g

This is a partial implementation, only g[index] = value will work.
I'm currently re-writing a Perl script into Python and with Perl I was
free to assign any element in the array without having to fill in the
previous elements. I can't seem to do that in Python...unless I'm
doing it wrong.


As already pointed out, a mechanical translation will yield substandard
results. As you did not describe the problem you are solving with the
"autogrowin g" list, there is little chance for us to come up with a better
or at least more idiomatic approach.

Peter

PS: Welcome to the worst programming language - except all others :-)


Jul 18 '05 #4
In article <br************ *@news.t-online.com>,
Peter Otten <__*******@web. de> wrote:
Matthew Sims wrote:
Is there anyway to assign to an element that wasn't defined in the
beginning? Like if I wanted element 5 assigned but not element 4
without using "" or None?


You can write your own class:

class GrowingList(lis t):
def __init__(self, seq, default=None):
list.__init__(s elf, seq)
self.default = default
def __setitem__(sel f, index, value):
if index >= len(self):
self.extend([self.default]*(index - len(self)))
self.append(val ue)
else:
list.__setitem_ _(self, index, value)
g = GrowingList(["alpha", "beta", "gamma"])
g[7] = "omega"
print g

This is a partial implementation, only g[index] = value will work.
I'm currently re-writing a Perl script into Python and with Perl I was
free to assign any element in the array without having to fill in the
previous elements. I can't seem to do that in Python...unless I'm
doing it wrong.


As already pointed out, a mechanical translation will yield substandard
results. As you did not describe the problem you are solving with the
"autogrowing " list, there is little chance for us to come up with a better
or at least more idiomatic approach.

Jul 18 '05 #5
"Francis Avila" <fr***********@ yahoo.com> wrote in message news:<vt******* *****@corp.supe rnews.com>...
Matthew Sims wrote in message
<1e************ **************@ posting.google. com>...
Python Newbie here. This is my first time learning object-oriented
programming and trying to break out of the usual Korn/Perl/PHP style
of programming. Having some difficulty understand some items.

For lists, I understand this:
C=["need","some"," help"]
print C[1]
some

But I can't seem to do this:
C[3]="here"

I know about C.append("here" ) but this brings me to my question...

Is there anyway to assign to an element that wasn't defined in the
beginning? Like if I wanted element 5 assigned but not element 4
without using "" or None?
I assume you tried 'insert'?
C=["need","some"," help"]
C.insert(10, 'here')
C ['need', 'some', 'help', 'here']

Ah, well that didn't work. Python has no (builtin) way to do what you want.
The reason isn't technical, but that the list needs *something* in that
intervening space, and Python isn't about to make rash presumptions about
what you want there ("explicit is better than implicit"). In choosing
between two behaviors for inserting to an index beyond the end of a list,
appending was deemed less surprising, less violent, and less likely to
introduce mysterious bugs than filling in the intermediate elements with
who-knows-what.


First off...I still have a lot to learn. :)

I can't even think of why one would want lists to have that sort of
behavior. It seems to me that if we're assigning to arbitrary elements and
we want the list to grow with it, that we should be using a different data
structure, like a dictionary with integer keys. The index of a list
generally has no semantic correlation to the data contained therein--it just
specifies order, and the data doesn't care about its own index. If we want
a semantic correlation, we make that correlation explicit by a dictionary's
key-value pair.

If you want to do this sort of thing (implicit assignment to intermediate
elements in list insertions), write a function to do it, or subclass list.
You can even modify the slice behavior itself (if you go the subclass
route), so that C[3] will silently act like perl instead of Python, but this
is *quite* unPythonic. (Other Python people reading your code will be
confused.)
My guess is that this is what makes OO programming different than
modular.

If this sort of answer surprises you (coming from perl, it might...), do an
"import this" at an interactive prompt and read. :)


The Zen of Python, by Tim Peters...heh
I'm currently re-writing a Perl script into Python and with Perl I was
free to assign any element in the array without having to fill in the
previous elements. I can't seem to do that in Python...unless I'm
doing it wrong.


Again, in general, Python has *no* implicit
assignments/declarations/modifications/etc. If you don't *explicitly* ask a
list to fill in its intermediate elements, Python won't do it. This is a
conscious design decision, and a great part of what makes Python Python.
For at least two senses of "great", IMO.

I could never learn perl (despite many attempts), so I ask, what does perl
do to the intermediate elements? Is a perl array more like a dictionary
with implicit integer keys (so intermediate keys simply don't exist), or
does it fill in the intermediate elements with 0 or something like that? In
what perl idioms is this behavior useful? (I still mean to learn perl one
of these days, for shell scripting.)


Here's how the program basically worked. It's for a Tape Library with
a robot arm in the middle. There are 40 slots and each is represented
as an element in the array. If a tape was in one of the slots, that
element # corresponds to the slot # and the tape ID would show in that
element. All other elements represented blank slots. This allowed me
to control the robot arm to the exact slot a tape resides since all I
had to do was look at any elements that had tape IDs assigned.

So far the only way I could get this to work in Python was to insert
"" to represent an empty slot. But Python counts "" when I want to see
how many tapes are currently taking up slots "len(SLOTS) ". It would
always show 40. So I now know that I need to write code to tell Python
not to count "". Not too difficult.

I guess I'm realizing how I need to approach Python as my first OO.
I'm re-writing the script as sort of a training. The program works
flawlessly in Perl, I'm just doing it to learn. So far it has taken
less lines of code in Python to perform the same tasks in Perl...up
til this point. ;)

Anyways, I appreciate the responses. I have a better understand of
Python.

--Matt
Jul 18 '05 #6
On Mon, Dec 15, 2003 at 06:57:19PM -0800, Matthew Sims wrote:
[...]

So far the only way I could get this to work in Python was to insert
"" to represent an empty slot. But Python counts "" when I want to see
how many tapes are currently taking up slots "len(SLOTS) ". It would
always show 40. So I now know that I need to write code to tell Python
not to count "". Not too difficult.

I guess I'm realizing how I need to approach Python as my first OO.
I'm re-writing the script as sort of a training. The program works
flawlessly in Perl, I'm just doing it to learn. So far it has taken
less lines of code in Python to perform the same tasks in Perl...up
til this point. ;)


It sounds like your problem isn't OO, but the wrong choice of datastructure.
As someone else in this thread has already said, you want a dictionary
(known as a 'hash' in perl), not a list. Among other things, len(some_dict)
will give you the result you expect.

-Andrew.
Jul 18 '05 #7
ma**@killermook ie.org (Matthew Sims) wrote in message news:<1e******* *************** ****@posting.go ogle.com>...
For lists, I understand this:
C=["need","some"," help"]
print C[1]
some

But I can't seem to do this:
C[3]="here"

I know about C.append("here" ) but this brings me to my question...

Is there anyway to assign to an element that wasn't defined in the
beginning? Like if I wanted element 5 assigned but not element 4
without using "" or None?


You could try using a dictionary instead of a list. You could even
initialize the dict from the list:

l = ["just", "a", "suggestion "]
d = {}
for k,v in enumerate(l):
d[k] = v

d[10] = "here"

Of course, to get at the values now, you would need to iterate over
d.values(). Note that you won't necessarily get the values in sorted
order of keys. You would have to do that explicitly if you want.

--
Shalabh
Jul 18 '05 #8
Matthew Sims wrote in message
<1e************ **************@ posting.google. com>...
"Francis Avila" <fr***********@ yahoo.com> wrote in message news:<vt******* *****@corp.supe rnews.com>...
Matthew Sims wrote in message
<1e************ **************@ posting.google. com>...


Here's how the program basically worked. It's for a Tape Library with
a robot arm in the middle. There are 40 slots and each is represented
as an element in the array. If a tape was in one of the slots, that
element # corresponds to the slot # and the tape ID would show in that
element. All other elements represented blank slots. This allowed me
to control the robot arm to the exact slot a tape resides since all I
had to do was look at any elements that had tape IDs assigned.


Ah, I see. Well, that makes more sense. In this case it's *not* so
clear-cut whether to use a list or a dict (or whatever). A list is a
reasonable approach.

Right off the bat, I can think of a few:

- What you're doing now, but initializing an empty list to fixed length, eg,
tapearray = [None]*40. Now just use it (no need to worry about magically
extending the list as you add to random slots), but make sure you don't
modify the list with insert, append, extend, pop, etc., etc.: only perform
operations on its members.

Python doesn't do the implicit thing, so you're often well off by
preinitalizing data structures, as here. I simply say [None]*40 and your
entire original question disappears, because you were looking at the problem
in a perlish manner of "how do I use this array in a manner that doesn't
require me to declare its total size before I use it." Explicit is better
than implicit.

- Using a dict with integer keys. Because your tape array won't change in
size, and iterating over the whole thing looks to be the most common
operation (as opposed to random access), dict might not be the obvious
choice. But dicts are more flexable, and make explicit the importance of
the index. You don't need to initalize your dict because it will add
non-existent keys on assignment, but it's probably less of a hassle to do so
anyway, because it *will* raise a KeyError if you try to read a key it
doesn't have. To get around this, you need to subclass dict and make a
(commonly reimplemented) DefaultDict subclass, or make sure you consistently
use the setdefault method of your dict. I say just preinitalize the blasted
thing: tapearray = dict([(i, None) for i in range(40)]).

- Using a list of lists, with zeroth element of each sublist the slot
number. Now you don't have to worry about preinitalizing the list or
keeping the tape slots in order. I can't think of any advantage to this
approach, unless you need faster iteration with variable total length, and
don't need the slots to be ordered. Probably just use a dict.

- Write a TapeSlot class, a TapeArray class, and a TapeArrayVisito r class.
(I'm kidding! Don't do this.)

Of course, you can mix-and-match as your requirements demand. If slots need
more status information, you could use a dict of lists or a list of lists.
If slots have a set of operations proper to them, you can use a list of
TapeSlot objects; or you could wrap the interface to the tapearray in a
TapeArray class, and make slot access a hidden implementation detail.
So far the only way I could get this to work in Python was to insert
"" to represent an empty slot. But Python counts "" when I want to see
how many tapes are currently taking up slots "len(SLOTS) ". It would
always show 40. So I now know that I need to write code to tell Python
not to count "". Not too difficult.
Not at all:

len([tapeID for tapeID in tapearray if tapeID])

"If the item in tapearray is True (in a boolean context, '' is False) append
that item to a new list, then find the length of this new list."

I guess I'm realizing how I need to approach Python as my first OO.
I'm re-writing the script as sort of a training. The program works
flawlessly in Perl, I'm just doing it to learn. So far it has taken
less lines of code in Python to perform the same tasks in Perl...up
til this point. ;)


Unless you're doing relatively complex things that require a rich set of
data/semantics for tape slots and/or tape arrays, there's no reason to start
using objects to represent them: "Simple is better than complex." Some
people get drunk on OO. OO is useful, but can also add unnecessary
complexity and obscure what you're doing behind too many layers of
abstraction.

Finally, don't do line-of-code comparisons between Python and perl. Python
may be brief, but it is *not* terse, and will choose clarity over
more-magic-per-line. List comprehensions excepted. ;)

Ugh, I talk too much. Well, hope you like Python!
--
Francis Avila

Jul 18 '05 #9
Cameron Laird wrote:
We've probably convinced Mr. Sims that Python (and
object-oriented programming) is really, really hard,
particularly compared to Perl: we have to write
hairy Class definitions just to do the simplest
things.


Posting a piece of ugly code to meet a specification that is incomplete or
even wrong and at the same time showing Python in bad light compared to
Perl... I have to be more careful with my posts.

Peter
Jul 18 '05 #10

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

Similar topics

1
2476
by: Jamie Jackson | last post by:
I'm using showModalDialog() to popup a window with some long text, followed by a couple of form elements. The content of the popup scrolls, since the content is longer to than the window. However, when it first opens, it is positioned at the bottom of the modal window's content, so one has to scroll to see the beginning of the content. It...
6
1686
by: Steve Lefevre | last post by:
Hey folks -- I have a series of selectboxes on a web form. I would like to have a javascript jump the focus to the next selectbox when the user presses a key. Each box has the values 1 through 6-9, depending. So normally someone who is used to it can just hit 1 <tab> 3<tab> 5<tab>1<tab>9<tab> -- I'd like to take the tabbing out. So...
1
2167
by: Jenny | last post by:
Hi, Can I create an array of tags by assigning same name to these tags? For example, I have two <p> tags with the same name t1. But document.all.b.value=document.all.t.length does not work. It works if the tags are <input type=radio...>. This line is OK:
2
11474
by: Scott Eade | last post by:
I am using select()/focus() to position the cursor at a particular field on a form. This works, but when the user presses the Tab key in IE the cursor jumps to the address bar rather than the next field (Firefox is fine). Does anyone know why this might be happening and how to stop it? Below is the code that I use to set the cursor...
8
2814
by: optimistx | last post by:
In excellent YAHOO user interface programs I see often extra parenthesis like this (foo=function(){ alert('I am foo'); })(); instead of bar=function(){
7
1756
by: Chris Lasher | last post by:
Hi all, I have a simple script: --- #!/usr/bin/env python a = 1 b = 2
9
2067
SamKL
by: SamKL | last post by:
Here's the page in question: http://www.primusint.info/test/index.php I've tested this in Mozilla, IE6, and IE7. In both IE6/7 it appears to be fine. No random jumping around or anything. Basically, in Firefox if you click around the navbar a few times it just ...seemingly... randomly makes the right section hop down a decent chunk of the...
1
1417
by: ranpelt | last post by:
Hi folks, After getting my page (http://theamazing.onlinewebshop.net/spotlight/) to work in Firefox and Safari. I thought I would try to get in working in IE. My attempt is here: http://theamazing.onlinewebshop.net/light/ Unfortunately, the transparent window is not enclosing the mouse position when the mouse is over the image. Also,...
20
1964
by: Prisoner at War | last post by:
Hi, People, Is it possible to have an "empty" or "dummy" <a href***without*** the browser jumping back up the page?? I have a hyperlink that doesn't point to another document, but is used to call forth a modal window onClick (or is there another way, without text or image links, of calling forth JavaScript on user activity??). I would...
0
7643
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. ...
0
7738
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5316
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...
0
4938
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...
0
3441
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...
0
3436
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1862
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
1
1004
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
688
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...

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.