Python Complex Number – Initialize, Access

Python Complex Number

Complex numbers are very common in scientific calculations. A complex number contains a real part and imaginary part.

Python supports complex numbers and has a datatype called complex.

Initialize Complex Number in Python

You can initialize a complex number in two ways. The first process is using complex() function. The second is initializing the variable with the actual value as shown below.

cn = complex(5,6)
cn = 5 + 6j

where 5 is the real part and 6 is the imaginary part. For the second method mentioned above, you have to mention j next to the imaginary part to tell Python that this is the imaginary part.

Type of Complex Number

In this example, we will print the complex number that we initialized in the above example and find the type of this variable.

Python Program

cn = 5 + 6j

Run this program


<class 'complex'>

The variable is of type complex.

Access Real and Imaginary Parts of Complex Number in Python

You can access the real part and imaginary part separately using dot operator. real property returns real part of the complex number while imag property returns imaginary part of the complex number.

In the following example, we shall initialize a complex number and print real and image parts separately.

Python Program

cn = complex(5, 6)

print('Real part is :',cn.real)
print('Imaginary part is :',cn.imag)
Run this program


Real part is : 5.0
Imaginary part is : 6.0


In this tutorial of Python Examples, we have learned about datatype complex in python, how to initialize a variable of complex datatype, how to access real and imaginary parts of complex number.