Comparing two lists and modifying one in Python

Question:

I have two lists J and Cond. For every True element in Cond, I want the corresponding element in J to be zero. I present the current and expected output.

J=[0, 2, 0, 6, 7, 9, 10]
Cond=[False, True, False, True, True, True, True]

for i in range(0,len(J)):
    if(Cond[i]==True):
        J[i]==0
print(J)

The current output is

[0, 2, 0, 6, 7, 9, 10]

The expected output is

[0, 0, 0, 0, 0, 0, 0]
Asked By: isaacmodi123

||

Answers:

Assignment is =, comparison for equality is ==, so you’ll want to do:

J = [0, 2, 0, 6, 7, 9, 10]
Cond = [False, True, False, True, True, True, True]

for i in range(len(J)):
    if Cond[i]:
        J[i] = 0

print(J)
Answered By: Jasmijn

If you want to do this in a cleaner manner, you can also do it with a list comprehension:

J=[0, 2, 0, 6, 7, 9, 10]
Cond=[False, True, False, True, True, True, True]

J = [(0 if not c else j) for j, c in zip(J, Cond)]

print(J)

modifying lists while looping over them can be a bad idea, so this is not just less code, it is also better practice. In this case, for example, you could also specify strict=True in the zip to trow an error if the lists are not of the same size.

Answered By: Egeau

For what you seem to be trying to do (setting all non-zero integers in a list to zero), having the Cond-list seems unnecessarily complicated. You could consider using this simple solution instead:

j = [0]*len(j)

Also consider using lowercase for your variable names, as that is the preferred way to do it in Python (quote from PEP 8, ie Python’s "standard" style guide):

Function and Variable Names

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Variable names follow the same convention as function names.

mixedCase is allowed only in contexts where that’s already the prevailing style (e.g. threading.py), to retain backwards compatibility.

Answered By: Jan van Wijk
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.