473,388 Members | 1,177 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

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 1315
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__(self, key, value):
py length = len(self.__list)
py if length < key:
py for i in range(length, key +1):
py self.__list.append(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
wi******@hotmail.com wrote:
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__(self, key, value):
py length = len(self.__list)
py if length < key:
py for i in range(length, key +1):
py self.__list.append(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
or like this
>>class Llist(list):
def __init__(self):
list.__init__(self)
def insertatindex(self, index, value):
lenght = len(self)
if lenght < index:
for i in range(lenght, index):
self.append(None)
self.insert(index, value)
Feb 6 '07 #11

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

Similar topics

3
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...
7
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
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...
4
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. ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.