Python complex function
last modified November 29, 2026 Python 3.15
In this article we show how the complex builtin creates a complex number, and how the resulting value is inspected and used.
A complex number has a real part and an imaginary part and is written 3+4j. The number is immutable, supports the usual arithmetic operators, and is stored as a pair of floats, so both parts are always available as .real and .imag.
The numeric types as a group are introduced in Python data types. The method that lets a custom class take part in complex() is described in Python __complex__ Method.
Zero, one, and two arguments
With no argument the result is zero. With one argument the value becomes the real part, and with two the second value becomes the imaginary part.
print(complex()) print(complex(2)) print(complex(2, 0.5)) print(complex(True, False)) print(complex(3 + 4j)) value = complex(2, -1) print(value) print(type(value))
The imaginary unit is written j in Python, not i. A complex number whose imaginary part is zero still prints with 0j, which keeps the type visible.
Passing an existing complex number copies it. Integers and booleans are converted to floats for both parts, so the result always stores two floats.
$ python construct.py 0j (2+0j) (2+0.5j) (1+0j) (3+4j) (2-1j) <class 'complex'>
Parsing a string
A single string argument is parsed as a complex literal. The surrounding parentheses and outer whitespace are optional, while spaces around the operator inside the literal are not allowed.
print(complex('1+2j'))
print(complex('(1+2j)'))
print(complex(' 1+2j '))
print(complex('-1.5e2+3j'))
for text in ['1 + 2j', '(1 + 2j)', '1+2i', 'falcon']:
try:
print(text, complex(text))
except ValueError as e:
print(text, 'ValueError:', e)
The forms are close to a complex literal and accept exponents and a sign on either part, but the string parser is stricter than the Python parser: an expression such as 1 + 2j is valid source code and still a malformed string here. Parentheses around the whole value are stripped before parsing.
The letter i is not accepted, and internal spaces make the string malformed. The error is always a ValueError with the message complex() arg is a malformed string, which does not say which character was wrong.
$ python from_string.py (1+2j) (1+2j) (1+2j) (-150+3j) 1 + 2j ValueError: complex() arg is a malformed string (1 + 2j) ValueError: complex() arg is a malformed string 1+2i ValueError: complex() arg is a malformed string falcon ValueError: complex() arg is a malformed string
Real part, imaginary part, conjugate
The two components are read-only attributes. The conjugate flips the sign of the imaginary part and returns a new number.
value = complex(3, 4) print(value.real) print(value.imag) print(value.conjugate()) print(complex(5).imag) print(complex(0, -2).conjugate()) real = value.real print(type(real).__name__)
Both parts are floats even when the constructor received integers, so 5 becomes 5.0 and the imaginary part of a real value is 0.0.
The attributes cannot be assigned; a different value needs a new complex number. That immutability is what allows the type to be hashed and used as a dictionary key.
$ python parts.py 3.0 4.0 (3-4j) 0.0 2j float
Equality and hashing
Two complex numbers are equal when both parts are equal, and a complex number with a zero imaginary part compares equal to the corresponding real number.
print(complex(3, 4) == 3 + 4j)
print(complex(2) == 2)
print(hash(complex(2)) == hash(2))
prices = {complex(2): 'two', complex(3, 1): 'three plus i'}
print(prices[2])
print(prices[3 + 1j])
try:
print(complex(1, 2) < complex(3, 4))
except TypeError as e:
print('TypeError:', e)
The equal hash means that an integer key and a complex key with the same value address the same dictionary entry. This follows from the numeric tower, where the types are compared by value.
Ordering is not defined for complex numbers, so the comparison operator raises TypeError. Sorting such values needs a key function, for example abs or key=lambda z: (z.real, z.imag).
$ python equality.py True True True two three plus i TypeError: '<' not supported between instances of 'complex' and 'complex'
Magnitude and formatting
The abs function returns the distance from the origin, and the format specification controls how the two parts are printed.
value = complex(3, 4)
print(abs(value))
print(abs(1 + 1j))
print(repr(value))
print(str(value))
print(f'{value}')
print(f'{value:.2f}')
print(format(value, '.1f'))
The magnitude of 3+4j is five, from the Pythagorean relation. It is always a float, because the square root is rarely exact.
The default representation and str are identical for complex numbers. A format specification such as .2f is applied to both parts, which makes a table of values line up without manual string building.
$ python magnitude.py 5.0 1.4142135623730951 (3+4j) (3+4j) (3+4j) 3.00+4.00j 3.0+4.0j
Polar coordinates with cmath
The cmath module converts between the rectangular form and the polar form, where an angle and a distance describe the same point.
import cmath import math value = complex(1, 1) print(cmath.phase(value)) print(cmath.polar(value)) print(cmath.rect(2, math.pi / 4)) magnitude, angle = cmath.polar(value) print(round(magnitude, 6), round(angle, 6)) back = cmath.rect(magnitude, angle) print(back == value) print(cmath.isclose(back, value))
phase returns the angle in radians and polar returns both the magnitude and the angle as a tuple. rect goes back from a magnitude and an angle to a complex number.
The round trip is not exact for this value: the reconstructed number differs from the original in the last bits, so == is False while cmath.isclose accepts the result. Trigonometric functions always introduce such errors, which is why complex values are compared with a tolerance.
$ python polar.py 0.7853981633974483 (1.4142135623730951, 0.7853981633974483) (1.4142135623730951+1.414213562373095j) 1.414214 0.785398 False True
Rotating a point
Multiplying by a complex number of magnitude one rotates another complex number around the origin. The angle of the multiplier becomes the rotation angle.
import cmath
import math
def rotate(point, degrees):
angle = math.radians(degrees)
spin = cmath.rect(1, angle)
value = complex(*point) * spin
return round(value.real, 12) + 0.0, round(value.imag, 12) + 0.0
print(rotate((3, 4), 90))
print(rotate((3, 4), 180))
print(rotate((5, 0), 45))
print(rotate((1, 0), 360))
A multiplier on the unit circle changes only the direction, not the distance from the origin. Each result has the same magnitude as the input point.
The rounding hides the tiny error that cos and sin leave in the last bits, so the table shows the intended coordinates. A full turn returns the original point.
$ python rotation.py (-4.0, 3.0) (-3.0, -4.0) (3.535533905933, 3.535533905933) (1.0, 0.0)
Objects that define __complex__
The constructor also accepts an object that implements __complex__. The method must return a complex number, and the constructor uses that value.
import cmath
import math
class Polar:
def __init__(self, radius, degrees):
self.radius = radius
self.degrees = degrees
def __complex__(self):
return cmath.rect(self.radius, math.radians(self.degrees))
point = Polar(2, 60)
print(complex(point))
print(abs(complex(point)))
print(type(complex(point)).__name__)
value = complex(point)
print(round(value.real, 6), round(value.imag, 6))
The class stores polar coordinates and converts itself on demand, so the rest of the program can treat it as a complex number without knowing the storage format.
A method that returns anything other than a complex number raises TypeError. The rules for the protocol, including the fallback to __float__ and __index__, are in Python __complex__ Method.
$ python dunder_complex.py (1.0000000000000002+1.7320508075688772j) 2.0 complex 1.0 1.732051
Source
Python complex() documentation
In this article we have built complex numbers from numbers and strings, read their parts, compared and hashed them, formatted them, converted them to polar coordinates, rotated points with them, and converted a custom object with __complex__. For the numeric types in general, see Python data types; for the protocol, see Python __complex__ Method.
Author
List all Python tutorials.