2

I am trying to check the elements of two lists in python to see if they contain the same values in the same position (indexes) of them. If an element let's say in position 0 of list A is not the same with the element in position 0 of list B I want to extract that value from list A and start again the comparison.

My program is below:

 listA = ["book","2","stage","me","you"]
 listB = ["stage","me","you"]

listB is always a sublist of listA!!

  diff_list = []
  for n in range(0, len(listA)):
     for k in range(0, len(listB)):
         if n == k:
            if listA[n] != listB[k]:
                 rm_item = listA.pop(n)
                 diff_list.append(rm_item)
                 k==0
                 print(k)

In my terminal first k = 0 then k = 1. Is there a way to remove the item from listA and then start the comparison again?

Thanks for the help guys! To be honest....What I wish to do is to get the difference between two strings. I have two texts where text B is always subtext of text A. So I used splitlines() to split the two texts and then I want compare the two lists to get what I want! Sorry but I am new to python and still can't figure out how a lot of things are done!

So I have

   textA='The first paragraph of the book is written well' 

and

   textB = 'the book is written well'

the result should be

  text_diff ='the first paragraph of' 
19
  • 1
    Why are you using two for-loops and then comparing to see if the values are equal? That can clearly be reduced to a single for loop. Commented May 13, 2015 at 15:53
  • 5
    I'm confused. You want to remove items from A until it looks like B? Why not just use B? Commented May 13, 2015 at 16:02
  • 4
    This looks like an X/Y problem. What is the actual task you're trying to complete? Commented May 13, 2015 at 16:03
  • 1
    @bettas I don't think we're quite sure what you're trying to do. What is the expected output? Commented May 13, 2015 at 16:05
  • 1
    can you please include your intended output, OP? Would help. Commented May 13, 2015 at 16:10

5 Answers 5

4

It seems to me that if you have two strings stringA and stringB (presumably lines from a larger text split on \n) such that stringB is always a substring of stringA, and you want to find the extra stuff in stringA, then it'd be easiest to do something like

stringA = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus aliquam leo odio, ut posuere dui rutrum ac. Nulla facilisi."
stringB = "ut posuere dui rutrum ac"

print stringA.replace(stringB, '')
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus aliquam leo odio, . Nulla facilisi."

Edit: Using your example text from the updated OP, you could do

textA = 'The first paragraph of the book is written well' 
textB = 'the book is written well'
text_diff = textA.lower().replace(textB.lower(), '')

which yields

'the first paragraph of'
Sign up to request clarification or add additional context in comments.

4 Comments

In the end, this is the correct answer. :) Nice job noticing the likelihood of the XY problem.
Oh my god @Shashank! it was indeed too easy...I feel stupid to have asked such a question!
@Shashank, indeed. Anytime there's that much confusion over what exactly OP wants, it's most likely XY.
@bettas To avoid further chaos, make sure to read about the XY problem. If you can learn from your experiences, you aren't stupid.
1

Try zip

>>> listA = ['Caesar', 'Pompey', 'Krassus']
>>> listB = ['Augustus', 'Pompey']
>>> for x,y in zip(listA, listB):
      print(x == y)

If you want to get all the values in listA not in listB, where order matters.

a_unique = [x[0] for x in zip(listA, listB) if x[0] != x[1]]

5 Comments

If I understand this correctly, it's to find all elements in A and B such that A[index] == B[index] and... exclude them? List comprehension added for the effect
There is a fundamental problem here because zip keeps pairing the i'th elements when you want to remove from A without advancing B.
Read the last sentence of the first paragraph of the question of this thread of this forum of ...
@tdelaney: hmm.. I understood "extract" such as to get the element, not to delete it. But you might be right; the TO is inexact on that.
@bettas: So I did not missinterpret your intention? Well, if I had known that ... ;-) Not that the lists must have equal lenght, otherwise you must a_unique.extend(listA[len(listB):]) (len(A) > len(B); if listB is longer, nothing changes.
0

If order is not important and you want to see the set difference of the two lists, you can use this:

print(list(set(listA) - set(listB)))

This outputs:

['2', 'book']

4 Comments

but this doesn't answer the question.
New answer has the potential problem that it doesn't preserve order.
@tdelaney Maybe pay attention to what I said. I say "if order is not important". The OP was extremely vague with what he wanted.
maybe try to answer OPs question.
0

Assuming that the sublist B is in the same order as list A you can do this:

listA = ["blabla", "book", "2", "stage", "me", "you"]
listB = ["stage", "me", "you"]

for i in range(len(listB)):
    if listA[i] != listB[i]:
        del listA[0]

print listA

And you don't really need to have a diff_list, at the end list A will be the same as list B.

1 Comment

That doesn't work if there are multiple elements in a row needing removal.
0

You can remove an element in the list by using remove. Use a try block in case it doesn't exist. The while True loop is to find duplicates in listA. Since the question has been clarified to find elements in A that are not in B, I have modified this.

diff_list = []
listA = ["book","2","stage","me","you"]
listB = ["stage","me","you"]
for k in listB:
    try:
        while True:
            listA.remove(k)
            print k
    except:
        diff_list.append(k)
print listA
print diff_list

Output

stage
me
you
['book', '2']
['stage', 'me', 'you']

4 Comments

What if some of the words are repeated? remove may get rid of a word that passed a previous compare.
I thought you wanted to remove all elements in A that matched B. including duplicates. If that is not the case, then remove the while True loop. It will then get rid of only the first match in A that is in B for all in list B.
Are you trying to remove elements in A that do NOT match an element in B?
@RobertJacobs please check again I have edited the question :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.