0

I have following condition:

a=[]
for i in list1:
    for j in list2:
        if i==j:
            a.append(i)

I want to add a statement a.append(np.nan) if i!=j after looping through list2. i.e
After iterating through inner for loop, if i don't find any i==j then it should append nan. PS.: I have such lists that there will be at-most once i==j.

How to do it?

3
  • Are you trying to find the intersection of two lists? Please don't do it like this. Commented Jun 19, 2018 at 6:18
  • 1
    I'd recommend something like this: set2 = set(list2); a = [i if i in set2 else 'nan' for i in list1] Commented Jun 19, 2018 at 6:20
  • Whats the desired output? Commented Jun 19, 2018 at 6:47

3 Answers 3

1

Try this:

import numpy as np
list1 = [1,2,3,4]
list2 = [2,1,3,5]
a = [i if i in list2 else np.nan for i in list1]
print(a)

Output:

[1, 2, 3, nan]
Sign up to request clarification or add additional context in comments.

Comments

1

You can easily do that with list comprehension.

a = [i if j == i else np.nan for i in list1 for j in list2]

First we assign i if i==j if it is not we assign np.nan. Then we iterate on list1 for i and list 2 for j

Comments

-1

After the if statement of i==j just return another condition after your if statement but on the same indent as your if statement, if will perform that operation in case your if statement is false.

a=[]
for i in list1:
   for j in list2:
      if i==j:
          a.append(i)  
      a.append(np.nan)

3 Comments

You cant do return outside a function or method
My bad, it wasn't supposed to be a return but rather an append to list in case i==j fails.
But that will append man to the list every time through the loop, which isn’t what is needed is it ?

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.