PythonPython Variables and Data TypesPython data types

What is a complex number in Python?

Question 34 of 88 · Updated

On this page

A complex number in Python is a numeric object with a real component and an imaginary component, represented by the built-in complex type. Mathematically, a complex number has the form a + bi, where i squared equals -1. Python uses j instead of i in imaginary literals.

For example, 3 + 4j represents a complex number with real part 3 and imaginary part 4. Complex numbers are useful for signal processing, electrical engineering, mathematical simulations, control systems and two-dimensional transformations.

Python supports complex arithmetic directly, without needing a third-party package.

1. Creating a complex number#

You can create a complex number with an imaginary literal or the built-in complex constructor.

PYTHON
z = 3 + 4j print(z.real, z.imag, type(z).__name__) print(complex(3, 4), complex('3+4j'))

Output:

3.0 4.0 complex
(3+4j) (3+4j)
ExpressionMeaning
3 + 4jA complex value with real part 3 and imaginary part 4
4jA purely imaginary value
1jThe imaginary unit
complex(3, 4)Construct a complex value from two real numeric arguments
complex('3+4j')Parse a supported complex-number string
complex(5)Convert a real number into a complex value with zero imaginary part

The real and imag attributes return floating-point components, even when the source literals are integers. Complex objects are immutable; assigning another value to z rebinds the name rather than editing its original object.

The expression 3 + 4j combines a real integer literal, an addition operator and an imaginary literal. A bare j is an ordinary identifier, not a predefined imaginary constant. Write 1j when you mean the imaginary unit.

The string constructor follows its own supported grammar. For instance, complex('3+4j') succeeds, whereas complex('3 + 4j') raises ValueError because of the internal spaces. Do not use eval to parse user-supplied numbers.

2. Complex numbers versus integers and floats#

TypeExampleRepresentation and purpose
int5Exact whole number, with arbitrary precision subject to resources
float5.5Finite-precision real number
complex3 + 4jPair of floating-point real and imaginary components

Complex numbers extend ordinary real arithmetic into a two-dimensional numerical plane. Unlike a float, a complex number does not represent a single ordered real quantity.

The two components have the same finite-precision limitations discussed in the preceding integer-versus-float lesson. Creating a complex object from a sufficiently large integer may lose precision or raise an overflow error.

3. Arithmetic with complex numbers#

Python supports addition, subtraction, multiplication, true division and exponentiation for complex numbers.

PYTHON
a = 3 + 4j b = 1 - 2j print(a+b, a-b, a*b, a/b)

Output:

(4+2j) (2+6j) (11-2j) (-1+2j)

Addition and subtraction operate on corresponding components. For multiplication, use the fact that j squared is -1:

  • Real component of the product: a*c - b*d.
  • Imaginary component of the product: a*d + b*c.

Here a + bj and c + dj are the two operands. For example, multiplying (3 + 4j) by (1 - 2j) gives real component 3*1 - 4*(-2) = 11 and imaginary component 3*(-2) + 4*1 = -2.

Mathematically, division by a nonzero complex number can be understood by multiplying numerator and denominator by the denominator's conjugate. Python's runtime implements complex division; manual implementations using squared magnitudes can introduce numerical overflow or underflow.

Floor division and modulo are not defined for ordinary Python complex operands. Division by 0j raises ZeroDivisionError.

4. Conjugate and magnitude#

The conjugate of a + bj is a - bj. The magnitude (or modulus) is the distance of the number from the origin in the complex plane.

For z = a + bj, its mathematical magnitude is the square root of a squared plus b squared.

PYTHON
z = 3 + 4j print(z.conjugate(), abs(z), z*z.conjugate())

Output:

(3-4j) 5.0 (25+0j)

The conjugate flips the sign of the imaginary component. Multiplying a complex number by its conjugate gives its squared magnitude mathematically. For finite-precision inputs, the computed product is subject to rounding and range limits.

Use abs(z) to calculate the magnitude rather than assuming that directly squaring both components and adding them is numerically robust. abs returns a float for ordinary complex inputs.

A complex number with imaginary component zero is still an object of type complex.

5. Rectangular and polar representation#

A complex number can be represented as a point in a plane, with its real component on the horizontal axis and imaginary component on the vertical axis.

Rectangular representation describes the point by its two components. Polar representation describes it by its magnitude r and phase angle theta, measured in radians relative to the positive real axis.

Loading diagram…

For 3 + 4j, the magnitude is 5 and the phase is approximately 0.927 radians. The two representations describe the same mathematical point; converting between them with floating-point arithmetic can introduce small rounding differences.

PYTHON
import cmath, math z = 3+4j r, theta = cmath.polar(z) print(round(r, 3), round(theta, 3)) print(cmath.isclose(cmath.rect(r, theta), z))

Output:

5.0 0.927
True

The cmath.phase function returns the phase directly. The cmath.rect function reconstructs a complex value from its polar coordinates, using cosine and sine of the supplied angle.

Use math.degrees to convert a phase in radians to degrees when needed for display. The numerical phase returned by cmath follows its documented principal-angle convention.

At zero magnitude, a geometric direction is not uniquely defined; do not treat the numerical phase of a zero-valued signal as a meaningful measurement of direction.

6. The cmath module#

Python's standard-library math module provides primarily real-valued mathematical operations. The cmath module provides mathematical functions suitable for complex arguments.

PYTHON
import cmath print(cmath.sqrt(-9)) print(cmath.isclose(cmath.exp(1j*cmath.pi), -1+0j, abs_tol=1e-12))

Output:

3j
True

The first result is the principal complex square root of -9. In contrast, math.sqrt(-9) raises ValueError in ordinary Python.

The second example evaluates Euler's identity numerically: e raised to i times pi equals -1 mathematically. A tolerance comparison is appropriate because floating-point sine and cosine calculations can introduce a small imaginary residual.

FunctionPurpose
cmath.sqrt(z)Principal complex square root
cmath.exp(z)Complex exponential
cmath.log(z)Complex logarithm
cmath.sin(z), cmath.cos(z)Complex trigonometric functions
cmath.phase(z)Principal phase angle
cmath.polar(z)Magnitude and phase
cmath.rect(r, theta)Convert polar coordinates to a complex number
cmath.isclose(a, b)Approximate numerical equality

Some mathematical functions have multiple possible complex values. The standard-library functions return values according to their documented principal branches and branch-cut conventions. For example, the sign of a zero imaginary component can matter when approaching a branch cut.

7. Mixed arithmetic, equality and truthiness#

PYTHON
print(2+3j+5, (2+3j)*0.5) print(3+0j == 3, bool(0j), bool(1j))

Output:

(7+3j) (1+1.5j)
True False True

Python supports mixed arithmetic between compatible built-in numeric types. A real integer or float can participate in complex arithmetic as a value whose imaginary component is zero.

Complex equality compares numerical values, so 3 + 0j compares equal to 3. A complex number is false in Boolean contexts when both components are zero; otherwise it is truthy.

Unlike real numbers, complex numbers do not have a natural total numerical ordering. Python does not support ordinary less-than or greater-than comparisons between complex numbers. Sorting complex values without an explicit ordering criterion therefore fails when such comparisons are required.

If a problem specifically requires sorting by magnitude, a suitable key is abs. If the problem requires lexicographic ordering by components, define that explicitly instead. These are application-specific ordering choices, not intrinsic complex-number ordering.

8. Precision and approximate equality#

PYTHON
import cmath print((0.1+0.2j)+(0.2+0.1j) == 0.3+0.3j) print(cmath.isclose((0.1+0.2j)+(0.2+0.1j), 0.3+0.3j))

Output:

False
True

Both components use floating-point arithmetic. Decimal fractions such as 0.1 and 0.2 are not represented exactly on typical binary floating-point systems.

cmath.isclose compares the magnitude of the difference against relative and absolute tolerance criteria. Select tolerances appropriate to the units and error budget of the calculation. Approximate equality is not a general substitute for exact equality, and it need not be transitive.

Complex objects can also contain non-finite floating-point components.

PYTHON
import cmath print(cmath.isfinite(complex(3,4)), cmath.isinf(complex(float('inf'),0)), cmath.isnan(complex(float('nan'),0)))

Output:

True True True

Validate finite inputs when a numerical application cannot meaningfully handle infinity or NaN. A finite complex value has finite real and imaginary components.

9. Practical example: rotate points by 90 degrees#

A two-dimensional point (x, y) can be represented as x + yj. Multiplying by 1j rotates that point counterclockwise by 90 degrees around the origin:

(x + yj) * j = -y + xj.

PYTHON
points = [1+0j, 2+1j, -1+2j] rotated = [point * 1j for point in points] print([(int(z.real), int(z.imag)) for z in rotated])

Output:

[(0, 1), (-1, 2), (-2, -1)]

For example, (2, 1) becomes (-1, 2). The integer conversions in the display are suitable for these small exact integral coordinates; they should not be applied indiscriminately to fractional or large coordinates.

For n points, this example performs O(n) fixed-size complex arithmetic operations and uses O(n) additional storage for the rotated collection and displayed coordinate pairs. The cost model assumes ordinary built-in complex values with bounded-size floating-point components.

For arbitrary-angle rotation, a unit complex factor can be constructed with cmath.rect(1, theta). This technique is useful in simulations and geometry, although floating-point rounding accumulates during repeated transformations. For large numerical arrays, consider appropriate vectorized numerical tools and benchmark the actual workload.

10. Practical example: serializing a complex number#

The standard JSON data model has no native complex-number type. A Python complex object must be converted to a supported representation before using the standard json encoder without a custom serialization hook.

PYTHON
import json z = 3+4j encoded = json.dumps({'real': z.real, 'imag': z.imag}) print(encoded) parts = json.loads(encoded) print(complex(parts['real'], parts['imag']) == z)

Output:

{"real": 3.0, "imag": 4.0}
True

This example defines an explicit object representation with real and imaginary fields. A production API should document that schema and validate field types, finite-value constraints and numeric range.

For strict JSON serialization of floating-point data, consider allow_nan=False when encoding and reject non-finite values during parsing and validation. JSON implementations and downstream numerical consumers may have different precision and range limits.

11. Common errors and troubleshooting#

MistakeCorrect approach
Writing a bare j or mathematical i as an imaginary literalUse 1j or another imaginary literal
Calling math.sqrt on a negative real argument when a complex root is intendedUse cmath.sqrt
Comparing complex numbers with less-than or greater-thanDefine an ordering criterion, such as magnitude
Calling int(z) or float(z) on a complex objectExplicitly inspect or validate z.real and z.imag
Expecting exact decimal arithmeticAccount for floating-point precision
Dividing by zero complex valueCheck the denominator and handle ZeroDivisionError
Serializing a complex object directly as JSONDefine a suitable representation

The following seven expressions were tested independently to confirm their expected failures:

PYTHON
import math import json (1+2j) < (2+3j) # TypeError int(3+0j) # TypeError float(3+0j) # TypeError complex("3 + 4j") # ValueError (1+2j) / 0j # ZeroDivisionError math.sqrt(-9) # ValueError json.dumps(1j) # TypeError

Run each expression separately or handle its exception; an uncaught exception stops normal sequential execution.

Even if the imaginary component is zero, int and float do not directly accept ordinary complex objects. If your application requires conversion to a real value, first check that the imaginary component satisfies the required zero or tolerance policy, then extract the real component. This avoids silently discarding information.

12. Frequently asked interview questions#

Why does Python use j rather than i?#

Python's imaginary literal syntax uses j or J, consistent with a convention used in engineering. The mathematical meaning is the same as i.

Are complex numbers mutable?#

No. Built-in complex objects are immutable. Their real and imaginary components are read-only attributes.

What is the difference between abs(z) and z.real?#

abs(z) returns the magnitude, while z.real returns the horizontal real component. For 3 + 4j these are 5.0 and 3.0 respectively.

Is a complex number with zero imaginary part equal to a real number?#

It can be numerically equal, for example 3 + 0j == 3, but its type is still complex.

Can complex numbers be dictionary keys?#

Yes, built-in complex objects are hashable. Numeric values that compare equal must have equal hashes, so numerically equal int, float and complex keys can refer to the same dictionary entry. Special NaN values require careful handling because their equality behaviour differs.

Are complex numbers always exact?#

No. Their components use floating-point representation, so rounding, overflow, underflow and special values are relevant.

Interview-ready answer#

A complex number in Python is a built-in immutable numeric object represented by a real and an imaginary floating-point component. It can be created using a literal such as 3 + 4j or complex(3, 4). Python supports complex addition, subtraction, multiplication, division and exponentiation. Use the real and imag attributes to inspect the components, conjugate() to obtain the conjugate, abs() for the magnitude, and cmath for complex mathematical functions and polar conversions. Complex numbers support equality but not intrinsic ordering comparisons. They are especially useful in signal processing, electrical engineering and two-dimensional mathematical transformations.

Key takeaways#

  • Python uses j in imaginary literals, with 1j representing the imaginary unit.
  • Complex values contain two floating-point components and are immutable.
  • Rectangular and polar representations describe the same complex value.
  • Use cmath for complex-valued mathematical functions and approximate comparisons.
  • Choose explicit policies for ordering, conversion, non-finite values and serialization.

Official references#

Verification note: Ten runnable examples and seven expected-exception tests passed locally on CPython 3.13.5. The Mermaid flowchart was manually reviewed for standard syntax and meaningful labels; no local Mermaid parser was available. Official reference links are supplied under the authorised offline research exception. Live documentation and public-site rendering were not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design