Convert Int to Complex in Python - Examples


Convert Int to Complex Number

To convert int to complex in Python, call complex() builtin function with the given int value passed as argument. Or else, we can add an imaginary part to the integer, so that the Python Interpreter would typecast it implicitly to complex datatype.

In this tutorial, we will learn how to convert int to complex numbers, with the above said two methods.


1. Convert Int to Complex using complex() built-in function

In this example, we will take an int value in variable a, convert it to complex type value and store it in output.

Python Program

#take an integer
a = 5
print('Input', a, type(a), sep='\n')

#convert int to complex
output = complex(a)
print('\nOutput', output, type(output), sep='\n')

Explanation

  1. The variable a is assigned an integer value of 5.
  2. The complex() function is called with a as its argument.
  3. Python converts the integer 5 into a complex number (5+0j) and assigns it to output.
  4. The types of a and output are printed to confirm the conversion.

Output

Input
5
<class 'int'>

Output
(5+0j)
<class 'complex'>

2. Implicit casting of int to complex

We can add 0 imaginary part and Python implicitly promotes the datatype to the higher type, which in this case from integer to complex.

Python Program

#take an integer
a = 5
print('Input', a, type(a), sep='\n')

#convert int to complex implicitly
output = a + 0j
print('\nOutput', output, type(output), sep='\n')

Explanation

  1. The variable a is assigned an integer value of 5.
  2. The integer a is added to 0j, representing a complex number with zero imaginary part.
  3. Python implicitly converts the result to a complex number (5+0j).
  4. The types of a and output are printed to confirm the implicit conversion.

Output

Input
5
<class 'int'>

Output
(5+0j)
<class 'complex'>

Summary

In this tutorial of Python Examples, we learned how to convert value of int datatype to value of complex datatype, with the help of well detailed example programs.




Python Libraries