Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python in vs ==. Which to Use in this case?

Tags:

python

I am making an AJAX call and passing variable pub in it which could be 1 or 0.

As a beginner I want to be double sure of the variable type that is coming in. I am aware I can easily convert to int() and the problem is actually not with AJAX result but it led to this question.

My code:

if pub == 1 or pub == '1':
    #execute funcA()

But the above is not so pythonic for me so I tried:

if pub in [1,'1']:
    #execute funcA()

Which of the above code is better in terms of:

  1. Performance(speed).
  2. Best practice.
  3. Memory usage.
like image 207
Yax Avatar asked Jul 15 '15 05:07

Yax


People also ask

What does == do in Python?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and !=

Is there a .equals in Python?

Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.

How do you check if two things are the same in Python?

Use the == operator to test if two variables are equal.

Is there any difference between 1 or 1 in Python?

The main difference between the 1 and 1. is in their type and type of the result of any equation that include float number in python will be float. That include addition subtraction multiplication exponents and even the integer division as if one operand is float answer will be of type float.

How do you compare two functions in Python?

Python - cmp() function cmp() is an in-built function in Python, it is used to compare two objects and returns value according to the given values. It does not return 'true' or 'false' instead of 'true' / 'false', it returns negative, zero or positive value based on the given input.


1 Answers

This code is better

if pub in [1,'1']:
    #execute funcA()

because it's slightly faster but mainly because it is not redundant. The variable pub appears only once there.

like image 174
dlask Avatar answered Sep 28 '22 01:09

dlask