Hi all,
I have 2 lists. What Im doing is check the first list and remove all
occurances of the elements in the second list from the first list, like so:
>>ps = [1,2,3,4,5,6,7,8 ,9,10,11,12,13, 14,15] qs = [6,7,8,9,10,11,1 2,1,2] for p in ps:
if p in qs:
ps.remove(p)
The problem Im having is that when I do
>>print ps
it gives me
[2, 3, 4, 5, 7, 9, 11, 13, 14, 15]
which is incorrect since 2,7,9,11 shouldnt be in that list. Is this a
bug in .remove? or is my algorithm somewhat flawed?
Thanks for your help!
Cheers
Astan 2 2510
Astan Chee:
(This is a small trap of Python, that it shares with some other
languages, and it shows that it may exist a language with a higher
level than Python.)
Generally in Python you can't modify a sequence that you are iterating
on.
There are some ways to avoid the problem. You can create a duplicate of
the ps list:
ps = [1,2,3,4,5,6,7,8 ,9,10,11,12,13, 14,15]
qs = [6,7,8,9,10,11,1 2,1,2]
for p in ps[:]:
if p in qs:
ps.remove(p)
print ps
Or:
for p in list(ps):
if p in qs:
ps.remove(p)
print ps
Or:
import copy
for p in copy.copy(ps):
if p in qs:
ps.remove(p)
print ps
Or you can adopt a different strategy:
print [el for el in ps if p not in qs]
This algorithm is O(n*m), so if the two lists are long, you may need
too much time to run that. To speed up the program you can do this
(Python 2.4):
sqs = set(qs)
print [el for el in ps if p not in sqs]
Bye,
bearophile
Astan Chee <st***@al.com.a uwrites on Sat, 19 Aug 2006 03:34:26 +1000:
>>for p in ps:
if p in qs:
ps.remove(p)
You are modifying an object ("ps") while you iterate over it.
This is a receipe for surprises...
The standard idiom is to iterate over a copy rather than the object itself:
for p in ps[:]:
....
Dieter This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Stan Cook |
last post by:
I was trying to take a list of files in a directory and remove all but the ".dbf" files. I used the following to try to remove the items, but they would not remove. Any help would be greatly appreciated.
x = 0
for each in _dbases:
if each <> ".dbf":
del each # also tried: del _dbases
x = x + 1
I must be doing something wrong, but it acts as though it is....
|
by: Ishwor |
last post by:
i am trying to remove an item 'e' from the list l but i keep getting IndexError.
I know the size of the list l is changing in the for loop & its sort
of trivial task but i found no other way than to suppress the
IndexError by doing a pass. any other ways you guys can suggest? Also
is this a good or bad habit in Python? someone may perhaps suggest a
better way which i am unaware of?? the deletion could be invoked from
user input (command...
|
by: Arne Claus |
last post by:
Hi
If've just read, that remove() on a list does not actually remove the
elements, but places them at the end of the list (according to TC++STL
by Josuttis). It also says, that remove returns a new, logical end
pointer, so that the following
myList::iterator end = myListObj.remove(myInt);
myListObj.erase(end, myListObj.end());
is possible and removes the "invalid" items at the end of the list.
|
by: sara |
last post by:
I am learning Access and programming. I wanted to have the user select
the departments for an ad from the list of all departments. Found code
(that I could understand) on this site, and it works. But I have 2
quesitons:
1. How can I REMOVE a selection from the Destination List box - and
keep the others there? My first code removes ALL from the Source list;
this code does nothing.
2. How can I now USE the data - I have to...
|
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
| |
by: SKP |
last post by:
Hi,
I am trying do a basic liked list program, where i am adding nodes at
the end. Adding part is fine, but removing part is not working.
Here is the code:
---------
#include<string>
class List {
struct node {
|
by: =?Utf-8?B?emhhbmdscg==?= |
last post by:
Hi,
Following code does not work. (it will crash.)-- I think the reason is that
I cannot modify list (call remove) in foreach. But I don't know what I can
do.
-----------------------------------------------------------------------
List<stringarstr = new List<string>();
//init data
for (int i = 0; i < 30; ++i)
|
by: AZRebelCowgirl73 |
last post by:
This is what I have so far:
My program!
import java.util.*;
import java.lang.*;
import java.io.*;
import ch06.lists.*;
public class UIandDB {
|
by: =?Utf-8?B?Sm9lbCBNZXJr?= |
last post by:
I have created a custom class with both value type members and reference type
members. I then have another custom class which inherits from a generic list
of my first class. This custom listneeds to support cloning:
Public Class RefClass
Public tcp As TcpClient
Public name As String
End Class
Public Class RefClassList
Inherits List(Of RefClass)
Implements ICloneable
|
by: isliguezze |
last post by:
template <class T>
class List {
public:
List();
List(const List&);
List(int, const T&);
void push_back(const T &);
void push_front(const T &);
void pop_back();
|
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...
| |
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,...
|
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...
|
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...
|
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...
|
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...
|
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();...
| |
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |