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.
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.
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])
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)
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]