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.
The elements of a list can be accessed by an index. To do that, you name the list, and then inside of a pair of square brackets you use an index number, like what I'm showing right here. 00:17 That allows access to individual elements within the list.
Each item in the list has a value(color name) and an index(its position in the list). Python uses zero-based indexing. That means, the first element(value 'red') has an index 0, the second(value 'green') has index 1, and so on.
“Indexing” means referring to an element of an iterable by its position within the iterable. “Slicing” means getting a subset of elements from an iterable based on their indices.
In logical indexing, you use a single, logical array for the matrix subscript. MATLAB extracts the matrix elements corresponding to the nonzero values of the logical array. The output is always in the form of a column vector. For example, A(A > 12) extracts all the elements of A that are greater than 12.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With