473,763 Members | 1,882 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to remove multiple occurrences of a string within a list?

Hi,

I have a list like ['0024', 'haha', '0024']
and as output I want ['haha']

If I
myList.remove(' 0024')

then only the first instance of '0024' is removed.

It seems like regular expressions is the rescue, but I couldn't find
the right tool.

Thanks!
bahoo

Apr 3 '07
37 19205

7stud wrote:
On Apr 3, 3:53 pm, "bahoo" <b83503...@yaho o.comwrote:
target = "0024"
l = ["0024", "haha", "0024"]
for index, val in enumerate(l):
if val==target:
del l[index]
print l
This latter suggestion (with the for loop) seems to be buggy: if there
are multiple items in the list "l" equal to "target", then only the
first one will be removed!

Thanks anyways.

Prove it.
here's something:
>>l = ["0024", "haha", "0024", "0024", "sfs"]
target = "0024"
for index, val in enumerate(l):
.... print "index: " , index , "value: " , val
.... del l[index]
.... print "after del: " , l
....
index: 0 value: 0024
after del: ['haha', '0024', '0024', 'sfs']
index: 1 value: 0024
after del: ['haha', '0024', 'sfs']
index: 2 value: sfs
after del: ['haha', '0024']
>>l
['haha', '0024']

Apr 4 '07 #21
On Apr 4, 2:20 am, "bahoo" <b83503...@yaho o.comwrote:
Hi,

I have a list like ['0024', 'haha', '0024']
and as output I want ['haha']

If I
myList.remove(' 0024')

then only the first instance of '0024' is removed.

It seems like regular expressions is the rescue, but I couldn't find
the right tool.

Thanks!
bahoo
how about this:
>>target = "0024"
l = ["0024", "haha", "0024", "0024", "sfs"]
result = [ item for item in l if item != target]
result
['haha', 'sfs']

Apr 4 '07 #22
How about:

list(frozenset(['0024', 'haha', '0024']))

mi*******@gmail .com schrieb:
On Apr 4, 2:20 am, "bahoo" <b83503...@yaho o.comwrote:
>Hi,

I have a list like ['0024', 'haha', '0024']
and as output I want ['haha']

If I
myList.remove( '0024')

then only the first instance of '0024' is removed.

It seems like regular expressions is the rescue, but I couldn't find
the right tool.

Thanks!
bahoo

how about this:
>>>target = "0024"
l = ["0024", "haha", "0024", "0024", "sfs"]
result = [ item for item in l if item != target]
result
['haha', 'sfs']
Apr 4 '07 #23
bahoo a écrit :
Hi,

I have a list like ['0024', 'haha', '0024']
and as output I want ['haha']

If I
myList.remove(' 0024')

then only the first instance of '0024' is removed.

It seems like regular expressions is the rescue,
Nope. re wouldn't help here - it works on strings, not on lists (you
need to understand that in Python, strings are *not* 'lists of chars').

Use list comps:
mylist = [item for item in mylist if item != '0024']

or filter() :
mylist = filter(lambda item: item != '0024', mylist)

but I couldn't find
the right tool.
May I second Grant Edward's suggestion in previous thread ? You'd really
do yourself a favor by following a couple Python tutorials. I'd say the
one in the official doc, and Dive into Python.
Apr 4 '07 #24
I don't think I would use sets at all. They change the semantic
meaning of the original list. What if you have duplicate entries that
you want to keep? Converting to a set and back will strip out the
duplicates of that.

Apr 4 '07 #25
On Apr 4, 3:08 am, Steven D'Aprano <s...@REMOVEME. cybersource.com .au>
wrote:
On Wed, 04 Apr 2007 00:59:23 -0700, 7stud wrote:
On Apr 3, 3:53 pm, "bahoo" <b83503...@yaho o.comwrote:
target = "0024"
l = ["0024", "haha", "0024"]
for index, val in enumerate(l):
if val==target:
del l[index]
print l
This latter suggestion (with the for loop) seems to be buggy: if there
are multiple items in the list "l" equal to "target", then only the
first one will be removed!
Thanks anyways.
Prove it.

Try replacing l = ["0024", "haha", "0024"]
with

l = ["0024", "0024", "haha"]

and re-running the code.

Actually, the description of the bug isn't quite right. The behaviour of
the for loop isn't defined -- sometimes it will work, sometimes it won't,
depending on how many items there are, and which of them are equal to the
target.
Thank you for the explanation.

Apr 4 '07 #26
"kyosohma" typed:
If you want to get really fancy, you could do a list comprehension
too:

your_list = ["0024","haha"," 0024"]
new_list = [i for i in your_list if i != '0024']
Or, just:

In [1]: l = ["0024","haha"," 0024"]
In [2]: filter(lambda x: x != "0024", l)
Out[2]: ['haha']

--
Ayaz Ahmed Khan

Do what comes naturally now. Seethe and fume and throw a tantrum.
Apr 4 '07 #27
Ayaz Ahmed Khan wrote:
"kyosohma" typed:
>If you want to get really fancy, you could do a list comprehension
too:

your_list = ["0024","haha"," 0024"]
new_list = [i for i in your_list if i != '0024']

Or, just:

In [1]: l = ["0024","haha"," 0024"]
In [2]: filter(lambda x: x != "0024", l)
Out[2]: ['haha']
Only if you want to make your code harder to read and slower::

$ python -m timeit -s "L = ['0024', 'haha', '0024']"
"[i for i in L if i != '0024']"
1000000 loops, best of 3: 0.679 usec per loop

$ python -m timeit -s "L = ['0024', 'haha', '0024']"
"filter(lam bda i: i != '1024', L)"
1000000 loops, best of 3: 1.38 usec per loop

There really isn't much use for filter() anymore. Even in the one place
I would have expected it to be faster, it's slower::

$ python -m timeit -s "L = ['', 'a', '', 'b']" "filter(Non e, L)"
1000000 loops, best of 3: 0.789 usec per loop

$ python -m timeit -s "L = ['', 'a', '', 'b']" "[i for i in L if i]"
1000000 loops, best of 3: 0.739 usec per loop

STeVe
Apr 4 '07 #28
In article <11************ **********@n59g 2000hsh.googleg roups.com>,
"bahoo" <b8*******@yaho o.comwrote:
Hi,

I have a list like ['0024', 'haha', '0024']
and as output I want ['haha']

If I
myList.remove(' 0024')

then only the first instance of '0024' is removed.

It seems like regular expressions is the rescue, but I couldn't find
the right tool.
If you know in advance which items are duplicated, then there have been
several simple solutions already proposed. Here's another way to tackle
the problem of removing ANY duplicated item from the list (i.e., any
string that appears 1 time).

def killdups(lst):
"""Filter duplicated elements from the input list, and return the
remaining (unique) items in their original order.
"""
count = {}
for elt in lst:
count[elt] = count.get(elt, 0) + 1
return [elt for elt in lst if count[elt] == 1]

This solution is not particularly tricky, but it has the nice properties
that:

1. It works on lists of any hashable type, not just strings,
2. It preserves the order of the unfiltered items,
3. It makes only two passes over the input list.

Cheers,
-M

--
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA
Apr 5 '07 #29
Amit Khemka <kh********@gma il.comwrote:
On 3 Apr 2007 11:20:33 -0700, bahoo <b8*******@yaho o.comwrote:
Hi,

I have a list like ['0024', 'haha', '0024']
and as output I want ['haha']

If I
myList.remove(' 0024')

then only the first instance of '0024' is removed.

To remove all items with multiple occurances in myList:

list(set(myList ) - set([x for x in myList if myList.count(x) >1]))
This approach is unfortunately quite inefficient, because each call to
myList.count is O(N), and there are O(N) such calls, so the whole thing
is O(N squared). [also, the inner square brackets are not needed, and
cause more memory to be consumed than omitting them would].
A "we-don't-need-no-stinkin'-one-liners" more relaxed approach:

import collections
d = collections.def aultdict(int)
for x in myList: d[x] += 1
list(x for x in myList if d[x]==1)

yields O(N) performance (give that dict-indexing is about O(1)...).
Collapsing this kind of approach back into a "one-liner" while keeping
the O(N) performance is not easy -- whether this is a fortunate or
unfortunate ocurrence is of course debatable. If we had a "turn
sequence into bag" function somewhere (and it might be worth having it
for other reasons):

def bagit(seq):
import collections
d = collections.def aultdict(int)
for x in seq: d[x] += 1
return d

then one-linerness might be achieved in the "gimme nonduplicated items"
task via a dirty, rotten trick...:

list(x for bag in [bagit(myList)] for x in myList if bag[x] == 1)

....which I would of course never mention in polite company...
Alex
Apr 5 '07 #30

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

Similar topics

12
5242
by: Kin®sole | last post by:
Hi I'm very new to VB (using VB6) I have two lists one blank and one containing names in the format of surname and then forename.I also have a combo box containing forenames.When I select a forename from my combo box I need to add the corresponding surname into the blank list box.What is the best way to do this? hope this make sense TIA
2
1972
by: mavis | last post by:
Could you please help me with this xsd definition? I need to define a set of elements occur in any order with multiple occurrences, but the same kind of elements need to group together... Sth like this.... <xs:element name="A"> <xs:complexType> <xs:all>
0
9389
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
10003
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
9943
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
8825
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
7370
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
5271
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...
1
3918
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
3529
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2797
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.