Tom
Tom

Reputation: 8800

Using append in an if statement

I don't get why the following two bits of code give different results:

x = [1,2,3]
y = [1,2,3,4]

if (x.append(4) == y) or (x == y):
    print(True, x, y)
else:
    print(False, x, y)

#prints True [1, 2, 3, 4] [1, 2, 3, 4]
x = [1,2,3]
y = [1,2,3,4]

if (x == y) or (x.append(4) == y):
    print(True, x, y)
else:
    print(False, x, y)

#prints False [1, 2, 3, 4] [1, 2, 3, 4]

Why does swapping the order of the two conditions give different results? x.append(4) makes x become [1,2,3,4], as is seen in either output. So it seems like the condition x.append(4) == y should be True in either case, satisfying the or of the if statement.

Upvotes: 0

Views: 964

Answers (1)

Tom
Tom

Reputation: 8800

There are two things going on here:

  • While x.append(4) does add 4 to x, the statement x.append(4) actually evaluates to None: append() doesn't return anything, it modifies objects in place. So if you had x.append(4) == None (with 4 or anything!) as a condition in the or statement, the if would always proceed.
  • x == y is the statement that is determining the evaluation of the condition (b/c of the first point). The order matters here because even though the append() statement evaluates to None, it still modifies x within the if line. So in the first case x==y is True b/c that statement comes after the append(), in the second x==y is False because it comes before the append().

This examples illustrates how the second can be modified to work like the first:

x = [1,2,3]
y = [1,2,3,4]

if (x == y) or (x.append(4) == y) or (x == y):
    print(True)
else:
    print(False)

#prints True
#the first (x==y) is False but the second is True!

Upvotes: 4

Related Questions