1
votes

I'm executing the following snippet on python 2.7:

i=0
j=3
a=['A','B','B','A']
while(a[i]=="A" & i<j):
    #do something

And I am getting this error.

TypeError: unsupported operand type(s) for &: 'str' and 'int'

Any help?

2
@JarrodRoberson: It might look similar but the operators are different, if you see. I wasn't aware that the solution would be similar for different operators. - Madhavi Jouhari

2 Answers

5
votes

& is "bitwise and" operand in Python , you should use and instead

from wiki.python.org:

x & y : Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.

"bitwise and" works like this:

>>> 1 & 0
0
>>> 0 & 0
0
>>> 1 & 1
1
-1
votes

You need to put brackets around the two conditions like below.

i=0
j=3
a=['A','B','B','A']
while((a[i]=="A") & (i<j)):
    #do something

refer below link for more detailed explanation Difference between 'and' (boolean) vs. '&' (bitwise) in python. Why difference in behavior with lists vs numpy arrays?