In Python, complex(real, imag) creates a complex number with a real part and an imaginary part: complex(3, 4) is (3+4j). You can also write the literal 3 + 4j, where j marks the imaginary unit.
complex("1+2j") parses a string, which must not contain spaces around the + or -. Both parts are stored as floats and are available as .real and .imag; abs() gives the magnitude.
complex is a built-in type (a class) that you call like a function: each call creates a new complex object. Like every built-in, it lives in the builtins module and is always available without an import.
Syntax
Give the two parts as numbers, or one string.
python
z = complex(real, imag)
z = complex("1+2j")
Call
What it does
complex(3, 4)
Returns (3+4j).
complex(2)
Returns (2+0j).
complex("1-2j")
Returns (1-2j).
complex()
Returns 0j.
Use the cmath module for square roots and other math on complex numbers; math.sqrt(-1) raises ValueError.
Library declarations
python
complex(real=0, imag=0)
complex(string, /)
# class complex: complex is a built-in type
Parameters
Parameter
Description
real
Optional. The real part (a number), or a string to parse. Default 0.
imag
Optional. The imaginary part. Not allowed when the first argument is a string. Default 0.
Return Value
Return Value
Description
complex
A complex number whose .real and .imag are floats.
Python Examples
Example 1 — Create a Complex Number and Read Its Parts
Build 3+4j, read both parts, and get its magnitude and conjugate.