Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Assign None or value

Tags:

python-2.7

Is there a short way to assign None or value in a variable, depending on the value?

x= value if value!= 999 else None
like image 858
pnina Avatar asked Mar 19 '17 14:03

pnina


People also ask

Is None a value in Python?

The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.

How do you define a null in Python?

null is often defined to be 0 in those languages, but null in Python is different. Python uses the keyword None to define null objects and variables. While None does serve some of the same purposes as null in other languages, it's another beast entirely.

Is None and == None Python?

In this case, they are the same. None is a singleton object (there only ever exists one None ). is checks to see if the object is the same object, while == just checks if they are equivalent. But since there is only one None , they will always be the same, and is will return True.


1 Answers

result = (on_false, on_true)[condition]

>>> value = 10
>>> x = (None,value)[value != 999]
>>> print x
10

>>> value = 999
>>> x = (None,value)[value != 999]
>>> print x
None
like image 89
Ajay Singh Avatar answered Nov 15 '22 12:11

Ajay Singh