473,772 Members | 2,349 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need help removing list elements.

This is python 2.4.3 on WinXP under PythonWin.

I have a config file with many blank lines and many other lines that I
don't need.

read the file in, splitlines to make a list, then run a loop that
looks like this:

config_file = open("lines.txt ", "rb")
returned_lines = config_file.rea d().splitlines( )

i = len(returned_li nes)
for i in range(i):
if returned_lines[i].find("Value") == -1:
if returned_lines[i].find("Name") == -1:
print "read in this useless line ..."
print returned_lines[i]
print "Removing line ..."
returned_lines[i] = ""


This blanks out all the lines I don't want. I did originally try 'del
returned_lines[i]' but I got list index out of range, so I made a loop
to delete the empty elements.

for i in range(i):
if returned_lines[i] == "":

del returned_lines[i]

But this gives me "IndexError : list out of range

After much experimentation and dumping of the list, I have figured out
that it doesn't like removing multiple empty elements in a row. In
other words, if there are 4 empty lines, it will remove one of them,
and seems to behave as though that was one element instead of 3. if I
make i = i - *number of groups of empty elements* it works without an
error, but leaves many empty elements behind.

Obviously I can iterate over it time and again, but that isn't how the
world should work.

Is this something obvious that I am doing wrong, or something more
complicated?

Any help will be gratefully appreciated!

Apr 29 '06 #1
5 2015
This looks like a job for list comprehensions:
returned_lines= ['Name: John, Value: 12','We don't want this one.','Name: Eric, Value: 24']
[x for x in returned_lines if ('Name' in x and 'Value' in x)]

['Name: John, Value: 12', 'Name: Eric, Value: 24']

List comprehensions are great. If you are not familiar with them, check
out the Python documentation. Once you get started with them, you won't
look back.

Apr 29 '06 #2
Ooops!

Looking at your example a bit closer, change the 'and' in the list
comprehension I posted to 'or', and it should do what you want.

Apr 29 '06 #3
nu*******@gmail .com wrote in
news:11******** **************@ j73g2000cwa.goo glegroups.com:
But this gives me "IndexError : list out of range


You are making the list shorter as you are iterating. By the time your
index is at the end of the original list, it isn't that long any more.
Creating a new list and appending the elements you want to keep avoids
the problem. Or you can just use a list comprehension(u ntested):

returned_lines=[line for line in open("lines.txt ", 'rb')
if line != ""]

or just

returned_lines=[line for line in open("lines.txt ") if line]

max
Apr 29 '06 #4
On 30/04/2006 12:22 AM, Max Erickson wrote:
nu*******@gmail .com wrote in
news:11******** **************@ j73g2000cwa.goo glegroups.com:
But this gives me "IndexError : list out of range
You are making the list shorter as you are iterating. By the time your
index is at the end of the original list, it isn't that long any more.


If you are hell-bent on conditionally deleting items from a list in
situ, you need to do it backwards:

for i in xrange(len(alis t)-1, -1, -1):
if not_interested( alist[i]):
del alist[i]
Creating a new list and appending the elements you want to keep avoids
the problem. Or you can just use a list comprehension(u ntested):

returned_lines=[line for line in open("lines.txt ", 'rb')
Call me crazy, but I wouldn't open the file in BINARY mode :-)
if line != ""]

or just

returned_lines=[line for line in open("lines.txt ") if line]


For a modicum of extra effort, the condition "if line.strip()" throws
away lines containing only whitespace.

However I don't see the point of creating a list of lines, then throwing
out only *some* of the uninteresting ones. IMHO the OP might be better
advised to read the file one line at a time, ignoring
blank/empty/comment lines, then *validate* the remainder. Hint: with the
semi-squished-list approach, you can't report the original line number
of any erroneous line without extra effort.

The OP might be even better advised to (read the source of, use) an
existing config file parser module.

Hope some of this helps,
John
Apr 29 '06 #5
Thanks to all those who responded. It has all helped immensely. :-)

I didn't know about list comprehensions before I started.

very warm regards to all.

Apr 30 '06 #6

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

Similar topics

1
2310
by: Tino | last post by:
I have a std::vector<int> which, after some initialization, has a fixed number of elements...after initialization I must do the following repeatedly: I remove an element which could be anywhere in the vector, and add another element which will always be at the end, ie. vector<int> v; int i, x; .... initialization
3
1678
by: pr10n | last post by:
Hello, all! I'm working on a personal blog and I'm trying to make it's markup more semantic, using the right elements, removing needless div's and so on. I was wondering if someone would be kind enough to peek at the code and see if they have any suggestions. I realize I am over using the list and header elements. I am also in the process of shifting the content blocks around in the code to get the meat of the site displayed first. ...
3
2728
by: Amit | last post by:
Hi, I have a list of integers. At each iteration, I remove some element from it and then insert new elements in it. The order of elements is not important. So I guess I could use a vector also for this purpose. However, I am also interested in having no duplicacy in elements of the vector. So I do not want to have any integer repeated more than once in the list. One very naive approach could be to compare the new integer being added to...
2
4742
by: vsgdp | last post by:
From what I learned, if you want to do random element insertions and deletions you should use a list. But, with std::vector, if the order of the elements does not matter, couldn't you efficiently remove a random element by swapping it with the last element and then just using pop_back? Does erase do this internally? Or does erase do the element shift to fill in the gap?
24
4399
by: RyanTaylor | last post by:
I have a final coming up later this week in my beginning Java class and my prof has decided to give us possible Javascript code we may have to write. Problem is, we didn't really cover JS and what we covered was within the last week of the class and all self taught. Our prof gave us an example of a Java method used to remove elements from an array: public void searchProcess() { int outIt=0;
7
2103
by: Adam Hartshorne | last post by:
Hi All, I was wondering if somebody could tell me if there is an efficient way to do the following. Say I have a list(or vector) A and a list B, I want to remove any elements in B, that are also elements in A. Adam
2
1712
by: Adam Hartshorne | last post by:
Hi All, I was wondering if somebody could tell me if there is an efficient way to do the following. Say I have a list(or vector) A and a list B, I want to remove any elements in B, that are also elements in A. Adam
10
6076
by: arnuld | last post by:
WANTED: /* C++ Primer - 4/e * * Exercise: 9.26 * STATEMENT * Using the following definition of ia, copy ia into a vector and into a list. Use the single iterator form of erase to remove the elements with odd values from your list * and the even values from your vector.
3
11591
m6s
by: m6s | last post by:
Hello to all, I am having trouble removing an item from list, which the item is a list by itself. <code> for self.line in self.filtered: if self.appid: if self.line <> self.appid: print RED + " ".join( map ( lambda x:str(x), self.filtered )) + RESET self.filtered.remove( self.line.index(self.line ) ) else: print "F: " + str(self.line)
0
9621
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
10264
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10039
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
9914
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
8937
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...
0
6716
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
5355
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...
2
3610
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2851
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.