473,890 Members | 1,732 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 1486
ei***********@y ahoo.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(i tem)
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...@mh39 1.invalidwrote:
eight02645...@y ahoo.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(i tem)
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...@y ahoo.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(e numerate(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(rid x+1, 'aword')
elif data[ridx] == 'd':
data.insert(rid x, 'dword')

print data

--
Hope this helps,
Steven

Apr 17 '07 #4
ei***********@y ahoo.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
2558
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, but try to use an iterator of a list that you're mutating and watch it all fall to pieces. That is, if you change the length of a section of the list through which the iterator has already passed, it will lose track of where it is. I think...
4
9534
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: 1. Am I correct in saying the above? 2. Implementing list as an array is part of language specification or implementation-dependent? 3. What if I actually need a doubly-linked list for constant-time
11
5806
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 substraction operator. Peeking in the algoritm header file it's clear why seeing that sort there calls _sort(_First, _Last, _Last-_First) which might be a tad challenging seeing that the different values stored in a list do not need to be stored...
10
15144
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 *enemydata; // Holds information about an enemy (in a game) // Its a double linked list node
5
6069
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 hits the right and left keys to move this insertion point (cursor) Here is the problem:
7
2618
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 children - when a child is fork()ed its pid is added to the linked list. I then have a SIGCHLD handler which is supposed to remove the pid from the list when a child exits. The problem I'm having is that very very occasionally and seemingly...
6
16138
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: struct node { int x; struct node *next; };
6
4026
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 a new object of class T, I would like to check if this object already exists in the list: meaning one having same integers. This can be done in linear time in a list, and probably faster if I use STL Set instead of list. I am wondering however if...
10
10521
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 between then what is the best solution.
6
5299
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 can do this with a linked list but is it possible to do the same thing with the standard containers? Thanks in advance, Carter.
0
9812
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,...
1
10899
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
9614
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
8004
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
7154
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
6032
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4655
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
2
4255
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3263
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.