473,738 Members | 5,934 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

modifying a list while iterating through

consider the following working loop where Packet is a subclass of
list, with Packet.insert(i ndex, iterable) inserting each item in
iterable into Packet at consecutive indexes starting at index.

i=0
while(i<len(pac ket)-4):
if packet[i:i+5]==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
else: i+=1

is there a way to do this more elegantly? seems like a big kludge.

Feb 26 '07 #1
4 2986
On Feb 25, 8:12 pm, dustin.g...@gma il.com wrote:
consider the following working loop where Packet is a subclass of
list, with Packet.insert(i ndex, iterable) inserting each item in
iterable into Packet at consecutive indexes starting at index.

i=0
while(i<len(pac ket)-4):
if packet[i:i+5]==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
else: i+=1

is there a way to do this more elegantly? seems like a big kludge.
Unless I missed something, this is a simple string replacement:

''.join(packet) .replace('01110 ', '0111001111')
George

Feb 26 '07 #2
On Feb 25, 5:12 pm, dustin.g...@gma il.com wrote:
consider the following working loop where Packet is a subclass of
list, with Packet.insert(i ndex, iterable) inserting each item in
iterable into Packet at consecutive indexes starting at index.

i=0
while(i<len(pac ket)-4):
if packet[i:i+5]==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
else: i+=1

is there a way to do this more elegantly? seems like a big kludge.

If Packet consists of '0's and '1's, then it may be
easier to convert to, or base the class on str (strings):

packet = "10101011110111 00111010001"
print "BEFORE ", packet
li = packet.split("0 1110")
packet = "0111001111".jo in(li)
print "AFTER ", packet

--
Hope this helps,
Steven

Feb 26 '07 #3
On Feb 25, 9:15 pm, attn.steven.... @gmail.com wrote:
On Feb 25, 5:12 pm, dustin.g...@gma il.com wrote:
consider the following working loop where Packet is a subclass of
list, with Packet.insert(i ndex, iterable) inserting each item in
iterable into Packet at consecutive indexes starting at index.
i=0
while(i<len(pac ket)-4):
if packet[i:i+5]==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
else: i+=1
is there a way to do this more elegantly? seems like a big kludge.

If Packet consists of '0's and '1's, then it may be
easier to convert to, or base the class on str (strings):

packet = "10101011110111 00111010001"
print "BEFORE ", packet
li = packet.split("0 1110")
packet = "0111001111".jo in(li)
print "AFTER ", packet

--
Hope this helps,
Steven


Steven, George,

Thanks for your responses. Yea, that would work.

My original question still stands, though, in situations where a
simple string replacement might not be sufficient. Is there a way to
insert into a list whilst iterating through it?

for example, consider a list of binary values.

for index in range(len(itera ble)):
item=iterable[index]
if item==1:
iterable.insert (index,0)

obv this wouldn't work because now all future indexes will be off by
the number of previously inserted items.

using a while loop to fix this ugly and counterintuitiv e.

Feb 26 '07 #4
On Mon, 26 Feb 2007 13:45:36 -0800, dustin.getz wrote:
My original question still stands, though, in situations where a
simple string replacement might not be sufficient. Is there a way to
insert into a list whilst iterating through it?
Inserting/deleting from a list while you're walking through it is *always*
tricky, by its very nature.

Deletions are easy to deal with: iterate over the list backwards. When
you delete the current item, the only items that are re-numbered are items
you've already looked at.

Similarly, if you iterate backwards over the list and make sure you only
insert after the current item, never before, you can avoid re-numbering
items you haven't looked at yet.

Another solution is to iterate over the list, creating a new list as you
go:

new = []
for item in some_list:
if condition:
# delete the item
pass
elif other_condition :
# insert something
new.extend(['something', item])
else:
new.append(item )


for example, consider a list of binary values.

for index in range(len(itera ble)):
item=iterable[index]
The Pythonic way to write that is

for index,item in enumerate(itera ble):
pass

if item==1:
iterable.insert (index,0)
"Iterables" are sequences and iterators -- anything you can iterate over.
In general, only sequences can be inserted into (and not even all
sequences).

obv this wouldn't work because now all future indexes will be off by the
number of previously inserted items.

using a while loop to fix this ugly and counterintuitiv e.
Well, if you insist on doing a tricky job, you're always going to have
tricky code. Here's one solution:

# inserting into a mutable sequence
sequence.revers e()
for index in range(len(seque nce)-1, -1, -1):
item = sequence[index]
if item == 1:
sequence.insert (index+1, 0)
sequence.revers e()
Here's a solution that should work for any iterable, provided you have
sufficient memory:

# inserting into a copy of iterable
copy = []
for item in iterable:
if item == 1:
copy.append(0)
copy.append(ite m)
Hope this helps.
--
Steven.

Feb 26 '07 #5

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

Similar topics

4
4538
by: Fernando Rodríguez | last post by:
Hi, While iterating through a list I'd like to know not just the current element, but also its index. Is there a better way than this: i = 0 newList = for element in aList: newList.append((i, element)) i += 1
4
4297
by: Paxton | last post by:
At the risk of being told "If it ain't broke, don't fix it", my code works, but is ugly. Part of the admin site I'm working on at the moment includes a facility for users to enter Formulations (recipes for making cosmetics etc) in 3 stages: Stage 1: basic info such as title, method etc and number of Phases (steps in recipe). Stage 2: dynamically generated form containing the exact number of phases as textboxes, depending on the number...
6
6055
by: Gustaf Liljegren | last post by:
I ran into this problem today: I got an array with Account objects. I need to iterate through this array to supplement the accounts in the array with more data. But the compiler complains when I try to modify the objects in the array while iterating through it. I marked the bugs in this code: // Loop through all previously added accounts foreach(Account a in a1) // a1 is an ArrayList { // If name and context is the same if(a.Name ==...
14
4336
by: Jacko | last post by:
Hi guys, Say I made a SELECT statement to my sql DB that would return 50 rows that I will use a sqldatareader to access. Instead of iterating through each and every row of the datareader, I'd like to just iterate through, say, rows 20 through 30. How can one do this?
10
15135
by: Ken Foster | last post by:
I have a hashtable keyed by some name, holding an instance of an object. Most of the time I use the hashtable in the traditional sense, given a name, I lookup the object, then I run a method on that object. Occaisionally however I need to run a method on every object in the hashtable. I've done both For..Each and iEnumeratior loops. The messy part is that under certain conditions, while iterating, a condition exists where I need to remove...
2
2167
by: Nick | last post by:
Hi all, Just a quick question. I have a class that exposes a number of fields (which are themselves custom types) through public properties. At run time, I have an object whom I'd like to check, is of same type as one of these fields. Is there a method or technique for iterating through a class's public properties, such as maybe using something from the reflection namespace?
2
7785
by: CamelR | last post by:
I have a newbie question, and I have seen reference to this mentioned in many places, but all just say "this has been discussed frequently in (other places) so we won't discuss it here..." and I am unable to find the actual answer... I expected : Array = , "/subdir2", , "/subdir3", ]]
5
12138
by: Alan | last post by:
I was wondering whether it is good programming practice or asking for trouble to modify a vector while iterating through it. That is, I want to do something like the following pseudocode in C++: for each element of the vector for each subsequent element of the vector if the belong together <some code to compare them> then merge the elements (add the 2nd to the 1st, then delete the 1st)
4
2819
RMWChaos
by: RMWChaos | last post by:
The next episode in the continuing saga of trying to develop a modular, automated DOM create and remove script asks the question, "Where should I put this code?" Alright, here's the story: with a great deal of help from gits, I've developed a DOM creation and deletion script, which can be used in multiple applications. You simply feed the script a JSON list of any size, and the script will create multiple DOM elements with as many attributes...
0
8788
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
9335
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
9263
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
9208
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6053
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
4570
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
4825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3279
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
3
2193
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.