0

I am trying to loop through a list. But it is getting the first element. It doesn't gets the second element. I can't figure out what i am doing wrong.

filte = ['fingerprint','cipher']
dupe = ['cipher','extract']

for val in filte:
    print(val)
    if val in dupe:
        dupe.remove(val)
    else:
        filte.remove(val)

print("filter",filte)
print("dupe",dupe)

output i got:

fingerprint
filter ['cipher']
dupe ['cipher', 'extract']

required output:

fingerprint
cipher
filter ['cipher']
dupe [ 'extract']
3
  • 1
    I don't exactly know how loops work in Python, but as you are removing an element during the loop, it mays bring an iterating issue. It's waiting for a second element, but after removing, cipher becomes the first one, so there is no second. Commented May 14, 2019 at 8:07
  • Exactly. So OP you want to either iterate on a reversed list (deleting its last element does not alter its indexes) or build a new list where you append the element that are suitable. Commented May 14, 2019 at 8:11
  • Could you explain @SmackAlpha what are you trying to do here? Commented May 14, 2019 at 8:24

2 Answers 2

3

Use set

Ex:

filte = ['fingerprint','cipher']
dupe = ['cipher','extract']

print(list(set(filte) - set(dupe)))  #OR list(set(filte).difference(set(dupe)))
print(list(set(dupe) - set(filte)))

Output:

['fingerprint']
['extract']

Note: Not a good practice to remove elements while iterating the object.

Sign up to request clarification or add additional context in comments.

Comments

0

just remove the else

filte = ['fingerprint','cipher']
dupe = ['cipher','extract']

for val in filte:
    print(val)
    if val in dupe:
        dupe.remove(val)
        filte.remove(val)

print("filter",filte)
print("dupe",dupe)

output:

fingerprint
cipher
filter ['fingerprint']
dupe ['extract']

Comments

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.