Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical indexing with lists

Tags:

python

list

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.

like image 355
user2320239 Avatar asked Apr 19 '16 14:04

user2320239


People also ask

Does indexing work with lists?

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.

Does indexing work with lists in Python?

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.

What is indexing in a list?

“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.

How do you use logical indexing?

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.


3 Answers

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])
like image 103
Sergei Lebedev Avatar answered Oct 22 '22 04:10

Sergei Lebedev


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)
like image 26
Padraic Cunningham Avatar answered Oct 22 '22 05:10

Padraic Cunningham


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]
like image 3
timgeb Avatar answered Oct 22 '22 04:10

timgeb