11

I have a program I'm looking through and with this section

temp = [1,2,3,4,5,6]
temp[temp!=1]=0
print temp

Which if run gives the result:

[1, 0, 3, 4, 5, 6]

I need help understanding what is going on in this code that leads to this result.

3 Answers 3

16

temp in your example is a list, which clearly is not equal to 1. Thus the expression

 temp[temp != 1] = 0

is actually

temp[True] = 0  # or, since booleans are also integers in CPython
temp[1] = 0

Convert temp to a NumPy array to get the broadcasting behaviour you need

>>> import numpy as np
>>> temp = np.array([1,2,3,4,5,6])
>>> temp[temp != 1] = 0
>>> temp 
array([1, 0, 0, 0, 0, 0])
8

As Already explained you are setting the second element using the result of comparing to a list which returns True/1 as bool is a subclass of int. You have a list not a numpy array so you need to iterate over it if you want to change it which you can do with a list comprehension using if/else logic:

temp = [1,2,3,4,5,6]
temp[:] = [0 if ele != 1 else ele for ele in temp ]

Which will give you:

[1, 0, 0, 0, 0, 0]

Or using a generator expression:

temp[:] = (0 if ele != 1 else ele for ele in temp)
4

If NumPy is not an option, use a list comprehension to build a new list.

>>> temp = [1,2,3,4,5,6]
>>> [int(x == 1) for x in temp]
[1, 0, 0, 0, 0, 0]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.