473,587 Members | 2,542 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

List Behavior when inserting new items

I'm looking to add an element to list of items, however I'd like to
add it at a specific index greater than the current size:

list = [1,2,3]
list.insert(10, 4)

What I'd like to see is something like:

[1,2,3,,,,,,4]

However I see:

[1,2,3,4]

Is there any way to produce this kind of behavior easily?

Thanks,
Drew

Jan 29 '07 #1
10 1327
Drew schrieb:
I'm looking to add an element to list of items, however I'd like to
add it at a specific index greater than the current size:

list = [1,2,3]
list.insert(10, 4)

What I'd like to see is something like:

[1,2,3,,,,,,4]

However I see:

[1,2,3,4]

Is there any way to produce this kind of behavior easily?
Use a dictionary?

If you know how large the list eventually will be, and that each
position is filled, you can also use range(n) to create a list.

What is your actual usecase?

diez
Jan 29 '07 #2
What is your actual usecase?
>
diez
The issue is that I don't know how long the list will eventually be.
Essentially I'm trying to use a 2D list to hold lines that I will
eventually print to the screen. Blank elements in the list will be
printed as spaces. I suppose every time I add an element, I could find
the difference between the size of the list and the desired index and
fill in the range between with " " values, however I just wanted to
see if there was a more natural way in the language.

Thanks,
Drew

Jan 29 '07 #3
On Jan 29, 7:57 pm, "Drew" <olso...@gmail. comwrote:
I'm looking to add an element to list of items, however I'd like to
add it at a specific index greater than the current size:

list = [1,2,3]
list.insert(10, 4)

What I'd like to see is something like:

[1,2,3,,,,,,4]

However I see:

[1,2,3,4]

Is there any way to produce this kind of behavior easily?

Thanks,
Drew
You could write your own class mimicing a list with your desired
behaviour, something like:

py>class llist(object):
py def __init__(self, arg = []):
py self.__list = arg
py def __setitem__(sel f, key, value):
py length = len(self.__list )
py if length < key:
py for i in range(length, key +1):
py self.__list.app end(None)
py self.__list[key] = value
py def __str__(self):
py return str(self.__list )
py>
py>x = llist()
py>x[10] = 1
py>print x
[None, None, None, None, None, None, None, None, None, None, 1]

for other methods to add to the llist class see http://docs.python.org/
ref/sequence-types.html

Jan 29 '07 #4
py def __init__(self, arg = []):
py self.__list = arg
Please don't perpetuate this bad habit!!! "arg=[]" is evaluated at
compile time, not runtime, and will give all default-inited llists the
same underlying list.

The correct idiom is:

def __init__(self, arg = None):
if arg is not None:
self.__list = arg
else:
self.__list = []

-- Paul

Jan 29 '07 #5


On Jan 29, 1:10 pm, "Drew" <olso...@gmail. comwrote:
What is your actual usecase?
diezThe issue is that I don't know how long the list will eventually be.
Essentially I'm trying to use a 2D list to hold lines that I will
eventually print to the screen. Blank elements in the list will be
printed as spaces. I suppose every time I add an element, I could find
the difference between the size of the list and the desired index and
fill in the range between with " " values, however I just wanted to
see if there was a more natural way in the language.
I would use DBR's suggestion to use a dictionary and only store
actual values. In this example, I'm making a histogram that only
ends up having results for 4,7,8,9,10 but I want the graph to show
the zero occurrences as well, so I just create them on the fly
when printing.

print
print 'tc factor of 2 distribution (* scale = 8)'
print
tchistkeys = tchist.keys()
tchistkeys.sort ()
prev_key = 0
for i in tchistkeys:
while prev_key<i:
print '%3d (%3d)' % (prev_key,0)
prev_key += 1
print '%3d (%3d)' % (i,tchist[i]),
hgraph = divmod(tchist[i],8)
s = '*'*(hgraph[0])
if hgraph[1]>0:
s = s + '.'
print s
prev_key += 1

## tc factor of 2 distribution (* scale = 8)
##
## 0 ( 0)
## 1 ( 0)
## 2 ( 0)
## 3 ( 0)
## 4 ( 1) .
## 5 ( 0)
## 6 ( 0)
## 7 (112) **************
## 8 (219) *************** ************.
## 9 ( 58) *******.
## 10 (110) *************.

>
Thanks,
Drew
Jan 29 '07 #6
Drew a écrit :
I'm looking to add an element to list of items, however I'd like to
add it at a specific index greater than the current size:

list = [1,2,3]
NB: better to avoid using builtins types and functions names as identifiers.
list.insert(10, 4)

What I'd like to see is something like:

[1,2,3,,,,,,4]
Hint : the Python representation of nothing is a singleton object named
None.
However I see:

[1,2,3,4]
Yeps. I thought it would have raised an IndexError. But I seldom use
list.insert() to append to a list - there's list.append() (and/or
list.extend()) for this.
Is there any way to produce this kind of behavior easily?
Hints:
>>[None] * 5
[None, None, None, None, None]
>>[1, 2, 3, None] + [10]
[1, 2, 3, None, 10]

HTH
Jan 29 '07 #7
Is there any way to produce this kind of behavior easily?Hints:
>>[None] * 5
[None, None, None, None, None]
>>[1, 2, 3, None] + [10]
[1, 2, 3, None, 10]

HTH
That is exactly what I was looking for. I'm actually working on some
problems at http://codgolf.com. I find it helps me to learn a language
and I'm coming from ruby where arrays have subtle differences from
python's lists. Thanks for all the helpful responses.

Jan 29 '07 #8
Drew a écrit :
>>What is your actual usecase?

diez


The issue is that I don't know how long the list will eventually be.
How is this an issue ? Python's lists are not fixed-sized arrays.
Essentially I'm trying to use a 2D list to hold lines that I will
eventually print to the screen.

Blank elements in the list will be
printed as spaces. I suppose every time I add an element, I could find
the difference between the size of the list and the desired index and
fill in the range between with " " values,
Yes. But note that [1,2,3,' ',' ',4]
is not the same thing as [1,2,3,,,4] (which is not valid Python FWIW).
however I just wanted to
see if there was a more natural way in the language.
I'm not sure I get it. Do you mean you're trying to use a list of lists
as a representation of a 2D matrix (IOW, a bitmap) ? Something like

bpm = [
['X',' ',' ',' ','X'],
[' ','X',' ','X',' '],
[' ',' ','X',' ',' '],
[' ','X',' ','X',' '],
['X',' ',' ',' ','X'],
]

If so, using dicts can be somewhat simpler and less memory-consuming:

d = {1:1, 2:2, 3:3}
d[10] = 4
for i in range(1, max(d.keys())+1 ):
print d.get(i, ' ')

That is, instead of storing useless spaces for "blank cells" and having
to do math to compute how many of them you have to insert/delete, you
just place stuff at desired indices, and 'fill in' spaces when printing
out to screen.

HTH
Jan 29 '07 #9
* Paul McGuire wrote:
>py def __init__(self, arg = []):
py self.__list = arg
Please don't perpetuate this bad habit!!! "arg=[]" is evaluated at
compile time, not runtime, and will give all default-inited llists the
same underlying list.
While this actually might be bad habit, the default arguments are *not*
eval'd at compile time. This seems to be a common mistake. They are
evaluated at runtime as everything else. The difference to other local
variables is, that the objects they're referring to are just initalized
once instead of each time they're taken into account.

nd
--
die (eval q-qq[Just Another Perl Hacker
]
;-)
# André Malo, <http://pub.perlig.de/#
Jan 30 '07 #10

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

Similar topics

3
22067
by: Andrew Clark | last post by:
*** post for FREE via your newsreader at post.newsfeed.com *** it's been a while since i have poseted to this newsgroup, but for a long time i was not programming at all. but now that i am out of college and facing the prospect of getting a real job, i need to get back into the game. anyway, i don't know if some of you know the stanford CS library. i took the problem set a while back and have recently rediscovered it adn have been trying...
7
2154
by: dam_fool_2003 | last post by:
friends, I wanted to learn the various ways of inserting a single list. so: Method 1: #include<stdlib.h> #include<stdio.h> struct node { unsigned int data; struct node *next;
44
3842
by: Josh Mcfarlane | last post by:
Just out of curiosity: When would using std::list be more efficient / effective than using other containers such as vector, deque, etc? As far as I'm aware, list doesn't appear to be specialized for anything. Thanks, Josh McFarlane
4
2972
by: dustin.getz | last post by:
consider the following working loop where Packet is a subclass of list, with Packet.insert(index, iterable) inserting each item in iterable into Packet at consecutive indexes starting at index. i=0 while(i<len(packet)-4): if packet==Packet("01110"): packet.insert(i, "01111") i+=10 #skip the 5 bits inserted, and skip the 5 bits just checked bc overlap should not trigger insertion
0
7927
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
8352
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
7981
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
6632
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
5723
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
5396
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
3846
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...
0
3882
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1194
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.