Python complex() Function: Syntax and 5 Examples

If you want to work with complex numbers in Python, the Python complex function is what you need. It takes a real and an imaginary part, or a number or string, and gives you back a complex number like (3+4j).

z = complex(3, 4)
print(z)        # (3+4j)
print(abs(z))   # 5.0

In this tutorial, I’ll take complex() from bare calls to string input, magnitude and phase, quadratic roots and custom objects, all run on Python 3.12.5 in Command Prompt.

Python complex() Syntax

complex(number=0, /)
complex(string, /)
complex(real=0, imag=0)
ParameterRequiredDefaultDescription
realNo0A number, or a string like "3+4j"
imagNo0The imaginary part (never a string)

Return value: a complex object. With no arguments you get 0j.

Note: complex() is one of the Python built-in functions, so there’s no import. String underscores like "1_000" need Python 3.6+.

When to Use complex() in Python

  • The real and imaginary parts sit in two variables
  • Reading values like "2-3j" from a CSV file
  • Impedance and AC phasor math
  • Quadratics with negative discriminants

For literals, cmath and the polar form, read my complex numbers in Python tutorial.

Example 1: Create a Complex Number in Python

Let me start with the four basic calls:

print(complex())
print(complex(5))
print(complex(3, 4))
print(complex(imag=-2.5))

z = complex(3, 4)
print(z.real, z.imag)

Output:

0j
(5+0j)
(3+4j)
-2.5j
3.0 4.0
Python complex function creating complex numbers with no arguments, one number, two numbers and imag only
Each call returns a complex object.

How does this work? complex(5) sets the imaginary part to 0. You always get floats from .real and .imag, so 3 came back as 3.0.

Example 2: Convert a String to a Complex Number

Here, I’ll convert text readings from a file:

readings = ["2.5-1.2j", " (1+2j) ", "4J", "1_000+5j", "-7.25"]
for text in readings:
    print(repr(text), "->", complex(text))

Output:

'2.5-1.2j' -> (2.5-1.2j)
' (1+2j) ' -> (1+2j)
'4J' -> 4j
'1_000+5j' -> (1000+5j)
'-7.25' -> (-7.25+0j)
Python complex function converting strings with parentheses, J suffix and underscores to complex numbers
Strings parse to complex values.

How does this work? Outer spaces and parentheses are ignored, and J works like j. A string with no imaginary part, like "-7.25", gives (-7.25+0j).

It’s the same idea as converting a string to a float in Python.

Example 3: Find the Magnitude and Phase of a Complex Number

Engineers write impedance as resistance plus reactance:

import cmath, math

# (resistance, reactance) in ohms, Chicago test lines
circuits = {"Line A": (50, 30), "Line B": (75, -40)}

for name, (r, x) in circuits.items():
    z = complex(r, x)
    angle = math.degrees(cmath.phase(z))
    print(f"{name}: {z}, |Z| = {abs(z):.2f}, {angle:.1f} deg")

Output:

Line A: (50+30j), |Z| = 58.31, 31.0 deg
Line B: (75-40j), |Z| = 85.00, -28.1 deg
Python complex numbers for circuit impedance with abs() magnitude and cmath.phase angle in degrees
Magnitude and phase per circuit.

How does this work? abs() returns the magnitude, as in absolute value in Python. cmath.phase() returns the phase of a complex number in radians, and math.degrees() converts it.

Example 4: Return Complex Roots from a Quadratic Equation

A negative discriminant means the roots aren’t real numbers:

import math

def complex_roots(a, b, c):
    d = b * b - 4 * a * c
    real = -b / (2 * a)
    imag = math.sqrt(-d) / (2 * a)
    return complex(real, imag), complex(real, -imag)

print(complex_roots(1, 2, 5))

Output:

((-1+2j), (-1-2j))
Python complex function returning complex roots of a quadratic equation with a negative discriminant
Two complex roots.

How does this work? For x² + 2x + 5, the discriminant is -16, so complex() built both roots. See how to solve a quadratic equation in Python for the full program.

Example 5: Convert Decimal, Fraction and Custom Objects with complex()

Complex Python projects often pass Decimal or custom objects:

from decimal import Decimal

class Phasor:
    def __init__(self, re, im):
        self.re, self.im = re, im

    def __complex__(self):
        return complex(self.re, self.im)

print(complex(Decimal("19.99")))
print(complex(Phasor(120, -15)))

Output:

(19.99+0j)
(120-15j)

How does this work? Decimal converts through __float__(), while Phasor defines __complex__(), which Python tries first.

Pro Tip: next, learn how to add two complex numbers in Python.

Common Mistakes with Python complex()

These four Python errors trip people up most:

tests = ['complex("1 + 2j")', 'complex("3+4i")',
         'complex("1+2j", 3)', 'complex(3, 4) < 5']
for expr in tests:
    try:
        eval(expr)
    except (ValueError, TypeError) as err:
        print(f"{type(err).__name__}: {err}")

Output:

ValueError: complex() arg is a malformed string
ValueError: complex() arg is a malformed string
TypeError: complex() can't take second arg if first is a string
TypeError: '<' not supported between instances of 'complex' and 'int'
Common Python complex function errors: ValueError for malformed strings and TypeError for string arguments
Real complex() errors.
  1. No spaces around + inside the string.
  2. Python uses j, not i.
  3. A string can’t take a second argument.
  4. Complex numbers can’t be ordered with <.

Wrapping Up the Python complex() Function

Python’s complex() turns numbers, strings and objects into complex values. Pair it with abs() and cmath; for big arrays, NumPy handles complex values too.

Next, browse more Python built-in functions and methods.

Try these related built-ins next:

What People Ask About Python complex() Function

What is complex() used for in Python?

It creates a complex number from parts, a number or a string.

How do I get the conjugate of a complex number?

Call z.conjugate(). For 3+4j it returns 3-4j.

Why does Python use j instead of i?

Python follows engineering, where i usually means current.

Can math.sqrt() return a complex number?

No. cmath.sqrt(-4) returns 2j, while math.sqrt(-4) raises ValueError.

How do I check if a value is complex?

Use isinstance(x, complex). See complex() in the Python docs.