473,507 Members | 2,447 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

list insertion question

hi
i have a list (after reading from a file), say
data = [ 'a','b','c','d','a','b','e','d']

I wanted to insert a word after every 'a', and before every 'd'. so i
use enumerate this list:
for num,item in enumerate(data):
if "a" in item:
data.insert(num+1,"aword")
if "d" in item:
data.insert(num-1,"dword") #this fails
but the above only inserts after 'a' but not before 'd'. What am i
doing wrong? is there better way?thanks

Apr 17 '07 #1
4 1472
ei***********@yahoo.com wrote:
hi
i have a list (after reading from a file), say
data = [ 'a','b','c','d','a','b','e','d']

I wanted to insert a word after every 'a', and before every 'd'. so i
use enumerate this list:
for num,item in enumerate(data):
if "a" in item:
data.insert(num+1,"aword")
if "d" in item:
data.insert(num-1,"dword") #this fails
but the above only inserts after 'a' but not before 'd'. What am i
doing wrong? is there better way?thanks
If you modify a list while you are iterating over it, you may get
unexpected results (an infinite loop in this case for me). Also ("a" in
item) will match "aword" since "a" is a component of it. I imagine you
mean (item == "a").

Try this:

output = []
for item in data:
if item == "d":
output.append("dword")
output.append(item)
if item == "a":
output.append("aword")
>>output
['a', 'aword', 'b', 'c', 'dword', 'd', 'a', 'aword', 'b', 'e', 'dword', 'd']
--
Michael Hoffman
Apr 17 '07 #2
On Apr 17, 9:47 am, Michael Hoffman <cam.ac...@mh391.invalidwrote:
eight02645...@yahoo.com wrote:
hi
i have a list (after reading from a file), say
data = [ 'a','b','c','d','a','b','e','d']
I wanted to insert a word after every 'a', and before every 'd'. so i
use enumerate this list:
for num,item in enumerate(data):
if "a" in item:
data.insert(num+1,"aword")
if "d" in item:
data.insert(num-1,"dword") #this fails
but the above only inserts after 'a' but not before 'd'. What am i
doing wrong? is there better way?thanks

If you modify a list while you are iterating over it, you may get
unexpected results (an infinite loop in this case for me). Also ("a" in
item) will match "aword" since "a" is a component of it. I imagine you
mean (item == "a").

Try this:

output = []
for item in data:
if item == "d":
output.append("dword")
output.append(item)
if item == "a":
output.append("aword")
>>output
['a', 'aword', 'b', 'c', 'dword', 'd', 'a', 'aword', 'b', 'e', 'dword', 'd']
--
Michael Hoffman
Infinite loop for me too! ^_^, should think of it b4 pressing F5.

Apr 17 '07 #3
On Apr 16, 6:05 pm, eight02645...@yahoo.com wrote:
hi
i have a list (after reading from a file), say
data = [ 'a','b','c','d','a','b','e','d']

I wanted to insert a word after every 'a', and before every 'd'. so i
use enumerate this list:
for num,item in enumerate(data):
if "a" in item:
data.insert(num+1,"aword")
if "d" in item:
data.insert(num-1,"dword") #this fails
but the above only inserts after 'a' but not before 'd'. What am i
doing wrong? is there better way?thanks

Traverse the list from highest index
to lowest index:

data = [ 'a', 'b', 'c', 'd', 'a', 'b', 'e', 'd' ]

print data
for idx, value in reversed(list(enumerate(data))):
if value == 'a':
data.insert(idx+1, 'aword')
elif value == 'd':
data.insert(idx, 'dword')

print data

# OR

last_idx = len(data) - 1

for idx in range(last_idx+1):
ridx = last_idx - idx
if data[ridx] == 'a':
data.insert(ridx+1, 'aword')
elif data[ridx] == 'd':
data.insert(ridx, 'dword')

print data

--
Hope this helps,
Steven

Apr 17 '07 #4
ei***********@yahoo.com writes:
hi
i have a list (after reading from a file), say
data = [ 'a','b','c','d','a','b','e','d']

I wanted to insert a word after every 'a', and before every 'd'. so i
use enumerate this list:
for num,item in enumerate(data):
if "a" in item:
data.insert(num+1,"aword")
if "d" in item:
data.insert(num-1,"dword") #this fails
but the above only inserts after 'a' but not before 'd'. What am i
doing wrong? is there better way?thanks
As others have said, you're mutating the list while iterating through
it, which can give whacked results. Also, even if you operate on a
copy of the list, that algorithm uses quadratic time because of all
the insertions into the list. These days I like to write in the style

def g():
for w in data:
if 'd' in w: yield 'dword'
yield w
if 'a' in w: yield 'aword'
data = list(g(data))

instead of using list.append as someone else suggested. The iterator
approach is probably a bit slower but can be seen as a bit cleaner,
depending on your stylistic preferences.
Apr 17 '07 #5

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

Similar topics

9
2534
by: Jess Austin | last post by:
hi, I like the way that Python does lists, and I love the way it does iterators. But I've decided I don't like what it does with iterators of lists. Lists are supposed to be mutable sequences,...
4
9479
by: sj | last post by:
I believe the type "list" is implemented as an array of pointers. Thus, random access is an O(1) operation while insertion/deletion is an O(n) operation. That said, I have the following questions:...
11
5769
by: velthuijsen | last post by:
I tried taking a list and pass it through std::sort like the following: sort(Unsorted.begin(), Unsorted.end()); I got an error back stating that the list iterator doesn't have a binary...
10
15099
by: Kent | last post by:
Hi! I want to store data (of enemys in a game) as a linked list, each node will look something like the following: struct node { double x,y; // x and y position coordinates struct enemy...
5
6036
by: John N. | last post by:
Hi All, Here I have a linked list each containing a char and is double linked. Then I have a pointer to an item in that list which is the current insertion point. In this funtion, the user...
7
2597
by: Kieran Simkin | last post by:
Hi all, I'm having some trouble with a linked list function and was wondering if anyone could shed any light on it. Basically I have a singly-linked list which stores pid numbers of a process's...
6
16119
by: Julia | last post by:
I am trying to sort a linked list using insertion sort. I have seen a lot of ways to get around this problem but no time-efficient and space-efficient solution. This is what I have so far: ...
6
3987
by: Amit Bhatia | last post by:
Hi, I am not sure if this belongs to this group. Anyway, my question is as follows: I have a list (STL list) whose elements are pairs of integers (STL pairs, say objects of class T). When I create...
10
10476
by: Aditya | last post by:
Hi All, I would like to know how it is possible to insert a node in a linked list without using a temp_pointer. If the element is the first element then there is no problem but if it is in...
6
5271
by: Carter | last post by:
This is probably somewhat of a beginners question but I am unfamiliar with alot of aspects of C++. What is the correct way to append multiple STL containers together in constant time. Obviously you...
0
7223
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,...
0
7114
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...
0
7377
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...
0
5623
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,...
0
3191
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...
0
3179
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1544
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 ...
1
762
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
412
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...

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.