Python int too large to convert to c long ошибка

Introduction Welcome to another tutorial on python. In today's article, we will learn something new and different. Making our way through a detailed

Introduction

Welcome to another tutorial on python. In today’s article, we will learn something new and different. Making our way through a detailed python Exception handling series brings us today to OverflowError.

OverflowError: Python int too large to convert to C long is a typical error in python which occurs when you initialize too large integer. Currently, the maximum capacity of an integer is limited to sys.maxint. If you initialize the integers greater than it, an error will be raised. Let’s dive deeper to get the concepts clear about OverflowError.

What is OverflowError in Python?

Just like other programming languages, the OverflowError in python is raised when the result of an arithmetic operation is out of range. By this, we mean that when an arithmetic operation exceeds the limit of the variable type, we get an overflow error exception.

Let us go to the code section to understand OverflowError.

import math
e = 250000
m = math.exp(e)
print(m)

OUTPUT:-

Traceback (most recent call last):
   File "main.py", line 3, in 
     m = math.exp(e)
 OverflowError: math range error

Explanation of the code

In the above program of python, we can see that we are importing the math module. We are using the math module to calculate the exponential value, such as exp(10000). In mathematical terms, it means e10000, and the value of e is 2.7.

Thus we land up to give up the statement as 2.710000. However, when we are trying to calculate this, it will give the value as a result that is double and cannot print it. Therefore, it gives us an overflow exception. That is why we get it is out of range.

There are many types of OverflowError such as :

  1. OverflowError: math in range error.
  2. OverflowError: Python int too large to convert to C long.
  3. The result too large.

But in this tutorial, we will specifically deal with “OverflowError: Python int too large to convert to C long.”

This error occurs when data type value storage exceeds the range. Now let us demonstrate this value exceeds in data type values in the below example:

import time
current_time = [tm for tm in time.localtime()] 
print("The current data and time:",current_time)

time2 = (2**99)
print("The invalid time is:",time2)

current_time[3] = time2
time3 = time.asctime(current_time)
print(time3)

OUTPUT:-

The current data and time: [2021, 5, 18, 19, 1, 10, 1, 138, 0]
The invlaid time is: 618970019642690137449562112
 Traceback (most recent call last):
   File "D:c progxx.py", line 9, in 
     time3 = time.asctime(current_time)
OverflowError: Python int too large to convert to C long

Explanation of the code

  1. In the above program, we are printing the current time using the time module.
  2. When we are printing the current time, we are printing the current time using time.localtime() function which results in the output with [year, month, day, minutes, seconds… ].
  3. Then we are printing the value by changing the hours to a larger value limit it can store. Therefore when we are trying to print this value it will throw an error saying Python int is too large to convert to C long.
  4. This output gives overflow error because the time3 uses plain integer object and therefore it cannot take objects of arbitrary length.

Also Read | 2 Causes of TypeError: ‘Tuple’ Object is not Callable in Python

How to resolve OverflowError: Python int too large to convert to C long?

In the above program, we saw the OverflowError that occurred when the current value exceeds the limit value. So to handle this, we have to raise the OverflowError exception. Now let us see how to resolve this problem. First, let’s implement the exception handling in our code.

import time

try:
  current_time = [tm for tm in time.localtime()]
  print("The current data and time: ",current_time)

  time2 = (2**99)
  print("The invalid time is:",time2)

  current_time[3] = time2
  print(time.asctime(current_time))

except OverflowError as of:
print("After the Overflow error", of)

Output:

The current data and time: [2021, 5, 18, 19, 1, 10, 1, 138, 0]
The invlaid time is: 618970019642690137449562112
('After the Overflow error', OverflowError('Python int too large to convert to C long',))

Explanation of the code:

In the above code, we saw that we handled the OverflowError by using try and except blocks or exception handling as we did in the above program.

Also, Read | [Solved] ValueError: Setting an Array Element With A Sequence Easily

OverflowError: Python int too large to convert to C long in Pandas

Recently, while I was working with the panda’s module recently and I discovered an OverflowError: Python int too large to convert to C long. I was running a python script, where I have to convert a string column from a pandas df to int, using the astype(int) method. However, I got the error. The code was as follows:-

import pandas as pd

df = pd.DataFrame({'t': ['123456789985', '178965423698']})
df['int'] = df['test'].astype('int')

print(df['int'])

OUTPUT:-

OverflowError: Python int too large to convert to C long in Pandas

Resolving the problem

All you need to do was pass int64 as the parameter in astype method.

import pandas as pd

data_f = pd.DataFrame({'t': ['123456789985', '178965423698']})
data_f['int'] = data_f['test'].astype('int64')

print(data_f['int'])

OUTPUT:-

123456789985
178965423698

Conclusion

In this article, we conclude that an overflow error is an error that occurs when the current runtime value obtained by the Python program exceeds the limit value. Also, we saw this error occurs when we use arithmetic operations in the program and the result exceeds the limit range value.

We also saw this error occurs when we are trying to convert from one data type to another when the value is larger than the given data type storage range. Lastly, we saw how to handle this error using exception handling i.e., try and except block.

If you come across any doubts feel free to comment down below. Till then keep pythoning geeks!

Python int is a data type that represents an integer. An integer is a whole number, such as 0, 19, or -21.

The int data type represents whole numbers in Python and is the default data type for representing integers.

You can also create an int from a string by using the int() function. The int() function takes a string as its argument and returns the integer representation of the string.

What is OverflowError in Python?

Python OverflowError is an error that occurs when a mathematical operation or assignment exceeds the maximum value that a numeric type can hold. OverflowError is raised when an operation or assignment produces a result too large to be represented by the numeric type.

Here’s a quick example of how you can encounter an OverflowError in Python.

In the above example, we attempt to assign the 2 ** 999 to the data variable. However, the 2 ** 999 is too large to be represented by a Python int, so the Python interpreter will raise an OverflowError.

How OverflowError occurs in Python?

The OverflowError: Python int too large too convert to C long occurs when an integer value is too large to represent a long in C. This error can occur when you try to convert a large integer value to a long using the ctypes module.

The ctypes module allows you to call functions from a shared library or DLL using the foreign function interface (FFI). When calling a function from a shared library or DLL, the ctypes module converts Python data types to the corresponding C data types. For example, a Python int is converted to a C long when calling a C function.

However, if the Python int is too large to be represented as a C long, the ctypes module will raise an OverflowError when converting it.

OverflowError in Pandas

Python OverflowError also occurs when we use the pandas library to store int values. The int number has some end limit to which several int data can be stored. If the limit is exceeded, then an OverflowError occurs.

There are different types of OverFlowError. Some of them can be math in range error, the result too large error, and Python int too large to convert to c long.

Example

import time

current = [t for t in time.localtime()] 
print(" The current data and time: ", current) 
t2 = (2**99)
print(" The invalid time is: ", t2)
current [3] = t2
t3 = time.asctime(tuple(current))
print(t3)

Output

OverflowError: Python int too large to convert to C long

In this example, an OverflowError occurs while assigning t3, which is Python int too large to convert to c long error. This is because the number exceeds the int range. This can be handled using try and except block.

To solve Python int too large to convert to c long OverflowError, convert an integer to int64 or use other types to store the values. Ensure that this number must be less than the int range. If it exceeds the int range, it will throw an OverflowError.

We can check whether the number is within the int range in the try block. If it exceeds, then the exception block is executed.

import time

try:
  current = [t for t in time.localtime()]
  print(" The current data and time: ", current)
  t2 = (2**99)
  print(" The invalid time is: ", t2)
  current[3] = t2
  t3 = time.asctime(tuple(current))
  print(t3)

except OverflowError as e:
  print("The error name is: ", e)

Output

The current data and time: [2022, 4, 7, 14, 3, 59, 3, 97, 0]
The invalid time is: 633825300114114700748351602688
The error name is: Python int too large to convert to C long

If we execute this program, the error message is displayed as:

The error name is: Python int too large to convert to c long

The OverflowError raises when you work with Pandas library. For example, the interpreter throws this error while storing a number greater than the int limit.

import pandas as pd 

df = pd.DataFrame({'Column_1': ['23845687891985972', '9823586793475672']})
df['int'] = df['Column_1'].astype('int') 
print(df['int'])

The OverflowError is raised because we convert the long number into an int. We can solve this problem by changing the astype to int64. But first, we can try if int64 can store that value. If not, we have to store it in another data type.

import pandas as pd 

df = pd.DataFrame({'Column_1': ['23845687891985972', '9823586793475672']})
df['int'] = df['Column_1'].astype('int64') 
print(df['int'])

Output

0 23845687891985972
1 9823586793475672

Name: int, dtype: int64

We can store this number in the int64 data type to resolve the error.

We can store any integer using the following command to get the maximum size.

import sys

print(sys.maxsize)

Output

You can see that it returns the maximum integer size for my computer. It is different from computer to computer. The number to be converted can be compared with this maximum size.

Conclusion

The OverflowError is raised when a mathematical operation or assignment exceeds the maximum value a numeric type can hold in Python.  Solve the error by converting the number to int64 instead of int. Another way is by using a try-except block.

That’s it for this tutorial.

See also

How to Solve ArithmeticError Exception in Python

TypeError: list indices must be integers or slices, not str in Python

ZeroDivisionError: division by zero in Python

Krunal Lathiya

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language. Krunal has experience with various programming languages and technologies, including PHP, Python, and JavaScript. He is comfortable working in front-end and back-end development.

  1. the OverflowError: Python int too large to convert to C long in Python
  2. Fix the OverflowError: Python int too large to convert to C long in Python

Python OverflowError: Python Int Too Large to Convert to C Long

This tutorial will demonstrate the OverflowError: python int too large to convert to c long error in Python.

the OverflowError: Python int too large to convert to C long in Python

An OverflowError is raised in Python when an arithmetic result exceeds the given limit of the data type. We encounter this specified error because we try to operate with an integer’s value more than the given range.

Code:

import numpy as np
arr = np.zeros((1, 2), dtype=int)
a = [6580225610007]
arr[0] = a

Output:

OverflowError: Python int too large to convert to C long

The above example creates an array of type int. We try to store a list containing an integer greater than the int type range.

The maximum size can also be checked using a constant from the sys library. This constant is available as sys.maxsize.

Fix the OverflowError: Python int too large to convert to C long in Python

To avoid this error, we must be mindful of the maximum range we can use with the int type. A fix exists, especially in this example regarding a numpy array.

The int type was equal to the long int type of the C language and was changed in Python 3, and the int type was converted to an arbitrary precision type.

However, the numpy library still uses it as declared in Python 2. The long int is usually platform-dependent, but for windows, it is always 32-bit.

To fix this error, we can use other types that are not platform-dependent. The most common alternative is the np.int64 type, and we specify this in the array with the dtype parameter.

Code:

import numpy as np
arr = np.zeros((1, 2), dtype=np.int64)
a = [6580225610007]
arr[0] = a
print(arr)

Output:

[[6580225610007 6580225610007]]

The above example shows that the error is resolved using the alternative type.

Another way can be to use a try and except block. These two blocks are used to work around exceptions in Python.

The code in the except block is executed if an exception is thrown in the try block.

Code:

import numpy as np
arr = np.zeros((1, 2), dtype=int)
a = [6580225610007]
try:
    arr[0] = a
except:
    print("Error in code")

Output:

The above example avoids the error using the try and except blocks. Remember that this is not a fix to the given error but a method to work around it.

Python OverflowError

Introduction to Python OverflowError

In Python, OverflowError occurs when any operations like arithmetic operations or any other variable storing any value above its limit then there occurs an overflow of values that will exceed it’s specified or already defined limit. In general, in all programming languages, this overflow error means the same. In Python also this error occurs when an arithmetic operation result is stored in any variable where the result value is larger than any given data type like float, int, etc exceeds the limit or value of current Python runtime values. Therefore when these values are larger than the declared data type values will result to raise memory errors.

How does Python OverflowError work?

Working of Overflow Error in Python:

In this article, we will see when and how this overflow error occurs in any Python program. An overflow error, in general, is as its name suggests which means overflow itself defines an extra part, therefore in Python also this occurs when an obtained value or result is larger than the declared operation or data type in the program then this throws an overflow error indicating the value is exceeding the given or declared limit value.

Examples to Implement Python OverflowError

Now let us see simple and general examples below:

Example #1

Code:

print("Simple program for showing overflow error")
print("n")
import math
print("The exponential value is")
print(math.exp(1000))

Output:

Python OverflowError1

Explanation: In the above program, we can see that we are declaring math module and using to calculate exponential value such as exp(1000) which means e^x here x value is 1000 and e value is 2.7 where when are trying to calculate this it will give value as a result which is double and it cannot print the result, therefore, it gives an overflow error as seen in the above program which says it is out of range because the x value is 1000 which when results give the value which is out of range or double to store the value and print it.

Example #2

Now we will see a program that will give an error due to data type value storage which exceeds the range. In the above program, we saw the arithmetic operation. Now let us demonstrate this value exceeds in data type values in the below example:

Code:

import time

currtime = [tm for tm in time.localtime()]
print("Print the current data and time")
print(currtime)
print("n")

time2 = (2**73)
print("The invlaid time is as follows:")
print(time2)
print("n")

currtime[3] = time2
time3 = time.asctime(currtime)
print(time3)

Output:

Python OverflowError2

Explanation: In the above program, we are printing the current time using the time module, when we are printing cure time in the program we are printing current time using time.local time() function which results in the output with [year, month, day, minutes, seconds… ] and then we are trying to print the value by changing the hours to a larger value the limit it can store. Therefore when we are trying to print this value it will throw an error saying Python int is too large to convert to C long. Where it means it cannot store such big value and convert it to the long data type. This output gives overflow error because the time3 uses plain integer object and therefore it cannot take objects of arbitrary length. These errors can be handled by using exception handling. In the below section we will see about this exception handling. In the above programs, we saw the Overflow error that occurred when the current value exceeds the limit value. So to handle this we have to raise overflowError exception. This exception in hierarchal found in order is BaseException, Exception, ArithmeticError, and then comes OverflowError. Now let us see the above programs on how to resolve this problem.

Example #3

Now let us see how we can handle the above math out of range as overflow error by using try and except exception handling in the below program. Code:

print("Simple program for showing overflow error")
print("n")

import math

try:
    print("The exponential value is")
    print(math.exp(1000))
    
except OverflowError as oe:
    print("After overflow", oe)

Output:

range as overflow

Explanation: So we can see in the above screenshot where we are handling the OverflowError by using try and except block and it will print the message when it throws this exception. We can see it in the above result output how the exception is handled.

Example #4

Let us see the solution of another program in the above section by using this exception handling concept. Let us demonstrate it below:

Code:

import time
try:
    currtime = [tm for tm in time.localtime()]
    print("Print the current data and time")
    print(currtime)
    print("n")
    
    time2 = (2**73)
    print("The invlaid time is as follows:")
    print(time2)
    print("n")
    currtime[3] = time2
    print(time.asctime(currtime))
except OverflowError as oe:
    print("After the Overflow error", oe)

Output:

exception handling concept

Explanation: In the above program, we can see that again we handled the OverflowError by using try and except blocks or exception handling as we did it in the above program.

Conclusion

In this article, we conclude that an overflow error is an error that occurs when the current runtime value obtained by the Python program exceeds the limit value. In this article, we saw this error occurs when we use arithmetic operations in the program and the result exceeds the limit range value. We also saw this error occurs when we are trying to convert from one data type to another when the value is larger than the given data type storage range. Lastly, we saw how to handle this error using exception handling using try and except block.

Recommended Articles

This is a guide to Python OverflowError. Here we discuss an introduction to Python OverflowError, how does it work with programming examples. You can also go through our other related articles to learn more –

  1. Python Exception Handling
  2. Queue in Python
  3. Python Curl
  4. Python Rest Server

Понравилась статья? Поделить с друзьями:
  • Python install numpy error
  • Python input output error
  • Python import syntax error
  • Python implementation error
  • Python if error try again