Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python complex() function

Reference for Python complex(): create complex numbers from real and imaginary parts or a string, use .real, .imag and conjugate(), and avoid the spaces trap.

The built-in complex type represents a number with a real part and an imaginary part, both stored as floats. Python writes the imaginary unit as j, so 3+4j is a complex literal. Calling complex() builds one from two numbers or from a string.

Complex numbers are used in signal processing, electrical engineering, fractals and anywhere square roots of negative numbers appear. The cmath module provides math functions for them.

Python
z = complex(3, 4)    # (3+4j)

Try it

Python Creating and inspecting complex numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python cmath and parsing pitfalls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
complex()
complex(real)
complex(real, imag)
complex(string)
Name Description
real Real part. Can be an int, float or another complex number. Default 0.
imag Imaginary part, same types. Default 0.
string A string like "3+4j". If a string is given, no second argument is allowed.

Return value: a complex number, equal to real + imag*1j.

Raises: ValueError for a malformed string (including spaces around the + or -); TypeError for unsupported types or when a string is combined with a second argument.

Usage notes

  • Attributes and methods. z.real and z.imag are floats; z.conjugate() flips the sign of the imaginary part.
  • Magnitude. abs(z) returns the distance from the origin as a float.
  • No ordering. Complex numbers cannot be compared with < or >; only == and != work.
  • Literals. 4j is a literal; j alone is a variable name. Write 1j for the imaginary unit.
  • Strings. The text form is strict: "1+2j" works, "1 + 2j" does not. Leading and trailing spaces are fine.
  • Float precision. Parts are 64-bit floats, so results show rounding, as with any float.
  • Math functions. math.sqrt(-1) raises ValueError; use cmath.sqrt(-1), which returns 1j. (-1) ** 0.5 also returns a complex number.
  • Polar form. cmath.polar(z) returns (r, phi), and cmath.rect(r, phi) goes back.