The complex() is a built-in function in Python that returns a complex number with the value of real and imaginary parts.

Python complex function:

The complex()function converts a string or a number to an equivalent complex number. However, if the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. But, the second parameter can never be a string. If both the parameters are a number, the first part will be considered real and the second as an imaginary part. Moreover, when converting from a string, the string must not contain s white space around the central + or – operator.


The signature for the complex() function is as shown below. It has two optional parameters.

complex(real, imag)

Parameters and return type

  • This function can take a string as a single parameter or two number parameters.
  • However, it returns a complex number with a real and an imaginary part.

Python Built-in Function complex Examples:

Example 1:  For this example, let us take a real and an imaginary as integer numbers.

real = 30
imag = 10
#Using complex and Printing
c1 = complex(real, imag)



Example 2: In this case, we will demonstrate the behavior of the complex function with one parameter and zero parameters. As a result, it will generate a complex number with an imaginary part as 0.

real = 3
imag = 5.5
#Using complex and Printing



Example 3: We will take two strings representing a complex number for this example. However, as the second string contains a space, it will raise an exception.

s2="3 + 7.5j"
#Using complex and Printing


Traceback (most recent call last):
  File "", line 4, in 
ValueError: complex() arg is a malformed string


Hence, the complex() function returns a complex number that contains a real part and an imaginary part generated from a number or a string. However, if string contains a white space, it will raise an exception.


Happy Learning 🙂