Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between int() and long()

What is the difference between int(x) and long(x) in python

My understanding:

  1. long() will always return a long
  2. int() will return an int or a long (if its too big)
  3. so int() is sufficient to dynamically get a int/long based on its value

So unless above (1) (2) (3) are incorrect, why do you need long()? when int() gets the job done? skipping long() for all number ranges will hurt me?


Documentation refered:

class int(x=0)

Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x is a number, it can be a plain integer, a long integer, or a floating point number. If x is floating point, the conversion truncates towards zero. If the argument is outside the integer range, the function returns a long object instead.

class long(x=0)

Return a long integer object constructed from a string or number x. If the argument is a string, it must contain a possibly signed number of arbitrary size, possibly embedded in whitespace. The base argument is interpreted in the same way as for int(), and may only be given when x is a string. Otherwise, the argument may be a plain or long integer or a floating point number, and a long integer with the same value is returned. Conversion of floating point numbers to integers truncates (towards zero). If no arguments are given, returns 0L.


code experimented

number = int(number_string) # cast it to integer
print number, "\t", type(number)

number = long(number_string) # cast it to long
print number, "\t", type(number)
like image 315
Srinath Ganesh Avatar asked Feb 04 '23 03:02

Srinath Ganesh


1 Answers

int: Integers; equivalent to C longs in Python 2.x, non-limited length in Python 3.x

long: Long integers of non-limited length; exists only in Python 2.x

So, in python 3.x and above, you can use int() instead of long().

like image 77
AlphaBet Avatar answered Feb 06 '23 16:02

AlphaBet