Python complex() function: Create and Work with Complex Numbers in Python


The complex() function in Python creates complex numbers using real and imaginary components. Complex numbers are commonly used in scientific computing, engineering applications, signal processing, and advanced mathematical operations.

Before diving deeper into the complex() function, you may want to review our comprehensive guides on Type Casting and Explicit Type Casting to better understand how Python handles data type conversions.

Whether you’re performing mathematical calculations, working with electrical systems, building simulations, or analyzing scientific data, understanding how the Python complex() function works is essential for writing accurate and reliable code.

To fully understand these concepts in action, let’s explore the key sections below:

By the end of this guide, you’ll be confident using the Python complex() function effectively, avoiding common errors, and applying best practices in real-world programming scenarios.

Syntax of Python complex() Function

complex([real[, imag]])

Parameter Description

Aspect Description
Parameters real — Optional numeric value for the real part (default 0).
imag — Optional numeric value for the imaginary part (default 0). Both must be numbers or numeric strings.
Returns A complex number in the form a + bj, where a is the real part and b is the imaginary part.
Error Handling
  • Raises TypeError if real or imag cannot be converted to a numeric type.
  • Passing non-numeric strings will raise ValueError.
  • Defaults (0) ensure no error when parameters are omitted.

Examples of Python complex() function

Explore these examples to see how complex() creates complex numbers from different inputs.

Example 1. Creating a Complex Number from Real and Imaginary Parts

number = complex(3, 4)
print(number)  # Output: (3+4j)

Explanation: The real part is 3 and the imaginary part is 4. Python represents it as (3+4j).

Example 2. Creating a Complex Number with Only Real Part

number = complex(5)
print(number)  # Output: (5+0j)

Explanation: If the imaginary part is omitted, it defaults to 0.

Example 3. Creating a Complex Number from Strings

number = complex("2", "3")
print(number)  # Output: (2+3j)

Explanation: Strings representing numbers can also be used to create complex numbers.

Example 4. Using Default Values

number = complex()
print(number)  # Output: 0j

Explanation: Calling complex() without arguments returns 0j (0 real and 0 imaginary).

Example 5. Operations with Complex Numbers

a = complex(2, 3)
b = complex(1, 4)

print(a + b)  # Output: (3+7j)
print(a * b)  # Output: (-10+11j)

Explanation: Complex numbers support arithmetic operations like addition, subtraction, multiplication, and division.

Invalid Scenarios: Python complex() Function

Understand the situations that cause errors to avoid unexpected ValueError or TypeError.

# Example 1: Non-numeric string for real part
# complex("abc", 1)   # Raises ValueError
Explanation:

Here’s what’s happening:

  • The first argument to complex() is “abc”, a string.
  • complex() expects numeric input (like int, float) or a string that represents a valid number, e.g., “3.14”.
  • “abc” cannot be converted to a number, so Python raises a ValueError.
# Example 2: Non-numeric string for imaginary part
# complex(3, "xyz")   # Raises ValueError

# Example 3: Passing a list as real part
# complex([1,2], 3)   # Raises TypeError

# Example 4: Passing a dictionary
# complex({"a": 1}, 2) # Raises TypeError

# Example 5: Passing None
# complex(None, 2)     # Raises TypeError

# Example 6: Passing unsupported object
# class MyObj: pass
# complex(MyObj(), 1)  # Raises TypeError
Explanation:
  • Example 2: "xyz" is an invalid string for the imaginary part, resulting in ValueError.
  • Example 3: Lists are not numeric, so passing [1,2] as the real part raises TypeError.
  • Example 4: Dictionaries cannot be converted to numbers, causing TypeError.
  • Example 5: None is not a numeric type, so using it as real or imaginary raises TypeError.
  • Example 6: Custom objects without numeric conversion support are invalid for complex(), raising TypeError.

Tip: Always ensure both real and imag parts are numeric values or strings that represent numbers to avoid errors.

Real-World Examples & Use Cases: Python complex() Function

See how complex numbers are applied in engineering, math and signal processing tasks.

1. Electrical Engineering – Impedance Calculation

resistance = 50
reactance = 20
impedance = complex(resistance, reactance)
print(impedance)  # Output: (50+20j)
Explanation:
  • The resistance represents the real part of impedance (Ohms).
  • The reactance represents the imaginary part (capacitive or inductive) of impedance.
  • complex(resistance, reactance) combines them into a complex number (50+20j).
  • This allows calculations with AC circuits using Python, such as adding impedances or computing current/voltage using Ohm’s law.

2. Signal Processing – Representing Phasors

phasor = complex(1, -1)
magnitude = abs(phasor)
print(magnitude)  # Output: 1.4142135623730951
Explanation:
  • The phasor represents a signal with magnitude and phase, encoded as a complex number (1-1j).
  • abs(phasor) computes the magnitude of the phasor using the formula √(real² + imag²).
  • Result 1.4142... is the Euclidean length of the phasor vector in the complex plane.
  • This technique is widely used in signal processing to handle oscillating signals efficiently.

3. Mathematical Operations – Complex Division

a = complex(2, 3)
b = complex(1, -1)
division = a / b
print(division)  # Output: (0.5+2.5j)
Explanation:
  • a and b are complex numbers (2+3j) and (1-1j) respectively.
  • The division a / b follows the standard complex number division formula: (a_real + a_imag*j) / (b_real + b_imag*j).
  • Python automatically computes the result as (0.5+2.5j), handling both real and imaginary components correctly.
  • This example illustrates using Python to perform complex arithmetic, useful in mathematics, physics, and engineering calculations.

Summary Table of complex() Conversions

Refer to this table for a quick overview of input types, examples, and their corresponding outputs.

Input Type Example Output
Real and Imaginary Numbers complex(3,4) (3+4j)
Real Number Only complex(5) (5+0j)
Strings Representing Numbers complex(“2”, “3”) (2+3j)
No Arguments complex() 0j
Invalid String complex(“abc”, “1”) ValueError
Invalid Type complex([1,2], 3) TypeError
Click on the topics below to explore more about Python str() function:

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top