-1

I have two lists

first = ['-6.50', '-7.00', '-6.00', '-7.50', '-5.50', '-4.50', '-4.00', '-5.00'] 
second = ['-7.50', '-4.50', '-4.00']

I want to shorten first by every element that occur in second list.

for i in first:
    for j in second:
        if i == j:
            first.remove(i)

Don't know why this did not remove the -4.00

['-6.50', '-7.00', '-6.00', '-5.50', '-4.00', '-5.00']

Any help appreciated :)

nutship
  • 4,624
  • 13
  • 47
  • 64
  • 1
    A comparison of all the methods suggested in the answers below. http://codebunk.com/bunk#-ItP66mNZpNolwb3ZNX5 – spicavigo Apr 30 '13 at 09:03
  • @spicavigo You'll need to run it on larger input to really see the difference. And move the setup lists out of the code too – jamylak Apr 30 '13 at 09:26

5 Answers5

3
>>> first = ['-6.50', '-7.00', '-6.00', '-7.50', '-5.50', '-4.50', '-4.00', '-5.00']
>>> second = ['-7.50', '-4.50', '-4.00']
>>> set_second = set(second) # the set is for fast O(1) amortized lookup
>>> [x for x in first if x not in set_second]
['-6.50', '-7.00', '-6.00', '-5.50', '-5.00']
jamylak
  • 128,818
  • 30
  • 231
  • 230
2

Don't modify sequences you are iterating through.

Shortest way to do this:

list(set(first) - set(second))
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

If you don't care about order, use

list(set(temp1) - set(temp2))

References: Get difference between two lists

Community
  • 1
  • 1
1

Try this code, and you will see that the -4.00s don't come side by side.:

for i in first:
    for j in second:
        print i,j,
        if i == j:
            print 'removed'
            first.remove(i)
        else:
            print
  • You shouldn't modify sequences you are iterating over.

TO solve your problem, just create a copy of your lists, which can be done by adding [:]:

for i in first[:]:
    for j in second[:]:
        if i == j:
            first.remove(i)

Another way to do this is:

[i for i in first if i not in second]
pradyunsg
  • 18,287
  • 11
  • 43
  • 96
1
l3 = [x for x in first if x not in second]
kiriloff
  • 25,609
  • 37
  • 148
  • 229