Vlary Nottellu
Vlary Nottellu

Reputation: 11

how does "list.append(val) or list" work?

While looking for how to allow list append() method to return the new list, I stumbled upon this solution:
list.append(val) or list
It's really nice and works for my use case, but I want to know how it does that.

Upvotes: 1

Views: 147

Answers (3)

Vlary Nottellu
Vlary Nottellu

Reputation: 11

x=[1]
s=None
print(x or s) #prints: [1]

for any future reference, this is how it works.
using x.append(2) or x it will append value, then when compared it will return the True statement between those two which is the list x=[1,2]

Upvotes: 0

chepner
chepner

Reputation: 530960

list.append(val) returns None, which is a falsey value, so the value of the entire expression is list. If list.append returned a truthy value, that would be the value of the or expression.

Upvotes: 0

Chris_Rands
Chris_Rands

Reputation: 41168

list.append(val) returns None, which is Falsy, and so triggers or and returns the list. Nonetheless I consider this not pythonic, just make two separate lines without or

Upvotes: 4

Related Questions