How do we use 'and' operator in array indexing?

Viewed 138

I found one code that used A[i][j] += min(A[i - 1][j and j - 1:j + 2]) I tried similar implementation as shown below which gave me unexpected results.Can anyone explain me? I am not able to understand how 'and' is interpreted in such situations.

a = [1,2,3,4,5,6,7,8,9,10,11,12]

print(a[0 and 3:4]) #[1, 2, 3, 4]

print(a[1 and 3:4]) #[4]

print(a[1 and 3:6]) #[4, 5, 6] 

print(a[0 and 3:6]) #[1, 2, 3, 4, 5, 6]

print(a[2 and 3:6]) #[4, 5, 6]

edit : in a[0 and 3:4] it includes elements from 0 to 3 but if I use a[1 and 3:4] it gives only 3rd element whereas I expect elements from 1 to 3

2 Answers

AND has higher precedence than slice : operator.

Your expressions works as,

a[0 and 3:4] --> a[(0 and 3):4] --> a[0:4] --> [1, 2, 3, 4]

You are simply comparing integer values by "and" in your case - not the values behind the index values. If you compare anything with 0, you get 0. In all the other cases, you get the value of the second integer (Maybe not for every python interpreter).

Related