Python Complex Number – Initialize, Access

Python Complex Number

Python supports complex numbers and has a datatype called complex.

A complex number contains a real part and imaginary part.

Complex numbers are very common in scientific calculations.

1. Initialize Complex number

We can initialize a complex number in two ways. The first process is using complex() function. The second is initializing the variable with the actual complex number.

In the following program, we initialize complex number cn in both the above mentioned ways.

Python Program

cn = complex(5,6)
print(cn)

cn = 5 + 6j
print(cn)
Run Code Copy

where 5 is the real part and 6 is the imaginary part.

complex() function takes real part and imaginary part as arguments respectively.

While assigning the actual complex number to a variable, we have to mention j next to the imaginary part to tell Python that this is the imaginary part.

2. 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 using type() builtin function.

Python Program

cn = 5 + 6j

print(cn)
print(type(cn))
Run Code Copy

Output

(5+6j)
<class 'complex'>

The variable is of type complex.

3. Access real and imaginary parts of Complex number

We can access the real part and imaginary part separately using dot operator.

  • real property of the complex number returns real part.
  • imag property of the complex number returns imaginary part.

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 Code Copy

Output

Real part is : 5.0
Imaginary part is : 6.0

Summary

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.

Code copied to clipboard successfully 👍