0

What is the name of the technique where there is a conditional is used in an index for a list but the variable in the conditional is a list itself? As you can see a is a list but it is used to check for corresponding elements in the list b.

>>> a = [ 1, 2, 3]
>>> b = [7, 7,7]

>>> b[a==1] = 8

>>> b
[8, 7, 7]

I was writing code using numpy arrays and thought of seeing if core Python included the same feature and it turns out it exists. I just had no way of searching for it because I didn't have the slightest idea of what it is called.

EDIT: I would like to know what is called and also an explanation of what is going on given the comments indicate that the code isn't doing what I think it is doing.

For clarity and elaboration, this is the code that I entered for numpy and got replacement similar to the Python list.

>>> import numpy as np
>>> lower_green = np.array([0,180,0]) 
>>> upper_green = np.array([100,255,100])
>>> upper_green[lower_green == 0] = 7
>>> upper_green
array([  7, 255,   7])
heretoinfinity
  • 1,528
  • 3
  • 14
  • 33

3 Answers3

6

Deconstructing the expression, we get:

  1. (False == 0) == True
  2. (a == 1) == False

Given this, we arrive at the conclusion that

b[a == 1] == b[False] == b[0]
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • thanks. I didn't see the logic here and made the wrong conclusion that indexing in python lists worked the same way as numpy indexing. – heretoinfinity Mar 01 '18 at 15:35
1

What you want to do can be achieved as follows (it will not work in all the cases):

a = [ 1, 2, 3]
b = [7, 7, 7]
b[a.index(1)] = 8

output:
b = [8, 7, 7]

However, the method index() returns only the lowest index if there are multiple matching elements. Therefore, it won't work in the following case:

a = [0, 1, 1]
b = [7, 7, 7]
b[a.index(1)] = 8

output:
b = [7, 8, 7] and not [7, 8, 8]

However, if you want to do it using core Python, here it goes (taking help from this answer):

# first get all the indices of the matching elements

a = [0, 1, 1]
b = [7, 7, 7]
to_match = 1
to_replace = 8

ind = [n for n,x in enumerate(a) if x == to_match]
for i in ind:
    b[i] = to_replace
Autonomous
  • 8,935
  • 1
  • 38
  • 77
1

a==1 is false, which is the same as zero

it's not the same as using an array of booleans in numpy[1]. (sometimes called logical indexing)

[1] https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html