-1

Program 1

list=[1,2,3,4]
A=3 in list
if A:
    print('True')

Program 2

list=[1,2,3,4]
if A=3 in list:
    print('True')

So I have these 2 programs. Program 1 runs fine and I understand why, but Program 2 doesn't. I thought that since A=3 in list returns true or false you could just embed it as part of a if loop, but I guess not. Why is that? What's going on here?

Community
  • 1
  • 1
malabeh
  • 101
  • 1
  • 2
  • 9
  • You are trying to assign value in if condition. I think that's not valid. – Tanveer Alam Dec 04 '14 at 07:14
  • Possible duplicate of http://stackoverflow.com/questions/2603956/can-we-have-assignment-in-a-condition – Sriram Dec 04 '14 at 07:18
  • This section from the official documentation will be useful - https://docs.python.org/2/tutorial/datastructures.html#more-on-conditions where it states that _"Note that in Python, unlike C, assignment cannot occur inside expressions. C programmers may grumble about this, but it avoids a common class of problems encountered in C programs: typing = in an expression when == was intended"_ – Sriram Dec 04 '14 at 07:19

5 Answers5

3

if A=3 in list: isn't valid syntax. You were probably looking for the raw boolean expression instead, if 3 in list.

As an aside, don't use list as your variable name. You're going to override the actual list method provided by Python.

Makoto
  • 104,088
  • 27
  • 192
  • 230
2

In Python assignments are statements rather than expressions, so they do not return any value. (more detail: Why does Python assignment not return a value?)

riotbit
  • 69
  • 4
0

See comments embedded in the program:

Program 1

list=[1,2,3,4]
# 3 in list evaluates to a boolean value, which is then assigned to the variable A
A=3 in list
if A:
    print('True')

Program 2

list=[1,2,3,4]
# Python does not allow this syntax as it is not "pythonic"
# Comparison A == 3 is a very common operation in an if statement
# and in other languages, assigning a variable in an if statement is allowed,
# As a consequence, this often results in very subtle bugs.
# Thus, Python does not allow this syntax to keep consistency and avoid these subtle bugs.
if A=3 in list:
    print('True')
Edward L.
  • 564
  • 2
  • 9
0

its simple you can not use assignmnent operation in if

like here

  A=3

python will read it as assignmnent and throw error

Avinash Garg
  • 1,374
  • 14
  • 18
0

The first example is equivalent to:

A = (3 in list)
#i.e. A is boolean, not an integer of value 3.

Second example is just invalid syntax.

Marcin
  • 215,873
  • 14
  • 235
  • 294