vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns str() in Python 2026: String Conversion + Modern Formatting & Best Practices type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns super() in Python 2026: Method Resolution & Modern Inheritance Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices round() in Python 2026: Rounding Numbers + Modern Precision & Use Cases reversed() in Python 2026: Reverse Iteration + Modern Patterns & Best Practices repr() in Python 2026: Official String Representation + Modern Debugging & Serialization Use Cases pow() in Python 2026: Power & Modular Exponentiation + Modern Use Cases & Best Practices property() in Python 2026: Properties, Getters/Setters & Modern Patterns ord() in Python 2026: Unicode Code Point from Character + Modern Use Cases & Best Practices open() in Python 2026: File Handling + Modern I/O Patterns & Best Practices range() in Python 2026: Efficient Sequence Generation + Modern Patterns & Best Practices print() in Python 2026: Output Formatting + Modern CLI & Debugging Patterns View all in this category →

complex() in Python 2026: Complex Number Creation & Modern Scientific Use Cases

Built In Function Mar 06, 2023

complex() in Python 2026: Complex Number Creation & Modern Scientific Use Cases

The built-in complex() function creates a complex number — either from real and imaginary parts or by parsing a string. In 2026 it remains a core tool for scientific computing, signal processing, electrical engineering, quantum simulation, control systems, and machine learning (especially in Fourier transforms, eigenvalue problems, and complex-valued neural networks).

With Python 3.12–3.14+ delivering faster complex arithmetic, better NumPy/JAX/PyTorch interop, and free-threading support for concurrent numeric code, complex numbers are more performant than ever. This March 23, 2026 update covers how complex() behaves today, creation patterns, real-world applications (signal processing, ML, physics), and best practices when combined with NumPy, JAX, or built-in math/cmath.

TL;DR — Key Takeaways 2026

  • complex(real, imag) → creates complex number (defaults imag=0)
  • String parsing: complex("1+2j") or complex("3-4j")
  • 2026 best practice: Use explicit real/imag args for clarity; prefer NumPy/JAX for array-level complex ops
  • Main use cases: signal processing (FFT), quantum mechanics, electrical engineering, complex-valued ML
  • Pair with cmath module for complex math functions
  • Performance: Fast C-level implementation — use array-based libs for large-scale work

1. Basic Usage — Creating Complex Numbers


# From real and imaginary parts
z1 = complex(3, 4)
print(z1)           # (3+4j)

# Real part only
z2 = complex(5)     # (5+0j)

# From string (common in config/parsing)
z3 = complex("1-2.5j")
print(z3)           # (1-2.5j)

# Zero
z4 = complex()      # 0j

2. Real-World Patterns in 2026

Signal Processing & FFT


import numpy as np

def fft_analysis(signal: list[float]) -> None:
    # Convert to complex for proper FFT
    complex_signal = [complex(x) for x in signal]
    spectrum = np.fft.fft(complex_signal)
    print("Magnitude:", np.abs(spectrum))

Complex-Valued Neural Networks (JAX 2026)


import jax.numpy as jnp

def complex_layer(x: jnp.ndarray) -> jnp.ndarray:
    # Weights can be complex
    w = jnp.array([complex(1, 0.5), complex(0, -1)])
    return jnp.dot(x, w)

Electrical Engineering – Phasors


def phasor(voltage: float, angle_deg: float) -> complex:
    angle_rad = np.deg2rad(angle_deg)
    return complex(voltage * np.cos(angle_rad), voltage * np.sin(angle_rad))

print(phasor(230, 30))  # ~ (199.18+115j)

3. complex() vs Alternatives – Comparison 2026

Method Input Output Best For
complex(real, imag)two numberscomplexExplicit real/imag creation
complex("1+2j")stringcomplexParsing config/user input
real + imag*1jtwo numberscomplexSimple inline creation
np.complex128(...)variouscomplex array/scalarNumPy/JAX/PyTorch workflows

4. Best Practices & Performance in 2026

  • Prefer explicit real/imag — complex(3, 4) is clearer than string parsing
  • Validate input — especially string parsing (can raise ValueError)
  • Type hints 2026:
    
    from typing import Union
    
    def create_phasor(mag: float, phase: float) -> complex:
        return complex(mag * np.cos(phase), mag * np.sin(phase))
    
  • Performance: complex() is C-optimized — negligible cost
  • Free-threading (3.14+): Safe — immutable result, no shared state issues
  • For arrays: Use NumPy/JAX complex128 dtype instead of list of complex

Worked Example: Working with Complex Numbers

A complex number has a real part and an imaginary part, both stored as floats. You can create one with complex() or with a literal such as 3+4j. The cmath module provides complex-aware versions of sqrt, exp, phase and polar, while abs() gives the magnitude. Complex numbers cannot be ordered, so < and > raise TypeError; compare magnitudes instead.

import cmath

z = complex(3, 4)
print(z.real, z.imag, abs(z))            # 3.0 4.0 5.0
print(z.conjugate(), z * z.conjugate())  # (3-4j) (25+0j)

r, phi = cmath.polar(z)
print(round(r, 2), round(phi, 4))        # 5.0 0.9273
print(cmath.rect(r, phi))                # back to approximately (3+4j)

print(cmath.sqrt(-1))                    # 1j
print(complex("2+3j") == 2 + 3j)         # True
try:
    complex("2 + 3j")                    # spaces are not allowed
except ValueError as exc:
    print("ValueError:", exc)
try:
    z < 1j
except TypeError:
    print("complex numbers are not ordered")

Common Mistakes

  • Using math.sqrt(-1): it raises ValueError; use cmath.sqrt
  • Putting spaces in strings passed to complex()
  • Comparing complex values with == after arithmetic: use cmath.isclose()

Quick Summary

  • complex(real, imag) or literals like 3+4j
  • abs() for magnitude, cmath for complex maths
  • No ordering; compare magnitudes or use isclose()

Conclusion — complex() in 2026: Scientific & Engineering Essential

complex() is the cleanest way to create complex numbers in Python — simple, fast, and precise. In 2026, use it for signal processing, phasor calculations, quantum simulation, complex-valued ML, and any domain involving magnitude + phase. Pair it with cmath for math functions and NumPy/JAX for vectorized work. It’s one of Python’s most reliable tools for numerical and scientific computing.

Next steps:

  • Replace any manual complex creation with complex(real, imag)

Related Tutorials

Share:
Last updated: March 2023
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices