Comparing two lists and removing elements which don't meet the criterion in Python

Question:

I have two lists J_new and C. For every True element of C, I want to remove the corresponding element in J_new. For instance, since C[0]=True, I want to remove J_new[0]=1. I present the current and expected outputs.

J_new = [1, 9, 15]
C=[True, True, False]

for i in range(0,len(C)): 
    if(C[i]=='True'):
        C[i]=[]
        J_new=J_new[C[i]]
print(J_new)

The current output is

[1, 9, 15]

The expected output is

[15]
Asked By: rajunarlikar123

||

Answers:

You can try this code for get required output:

J_new = [1, 9, 15]
C = [True, True, False]

J_new = [J_new[i] for i in range(len(C)) if not C[i]]

print(J_new)

Result:

[15]
Answered By: NIKUNJ KOTHIYA

When accessing parallel lists, always think "zip"!

>>> J_new = [1, 9, 15]
>>> C = [True, True, False]
>>> 
>>> [j for j, c in zip(J_new, C) if not c]
[15]
Answered By: J_H

#The code takes input from the user and splits it into a list of strings using the split() method. It then initializes a list ‘c’ with three boolean values.

j=list(input().split())
c=[True,True,False]

#The next line of code creates a new list ‘j’ by iterating over the original list ‘j’, selecting only the elements where the corresponding element of ‘c’ is False.

j=[j[i] for i in range(len(c)) if not c[i]]

#So, the resulting list ‘j’ contains only the elements of the original list ‘j’ at positions where the corresponding element of ‘c’ is False. In this case, since ‘c’ is [True, True, False], the third element of ‘j’ is excluded, and the resulting list ‘j’ contains only the first two elements of the original list.

Finally, the resulting list ‘j’ is printed.

print(j)

Answered By: Anurag Thorkar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.