Python complex() Function

Returns a complex number from either two numbers or a string. The real and imaginary components of the complex number can be accessed with the real and imag properties.


complex(real, imaginary = None)


real Required. The real portion of the complex number
imaginary Optional. The imaginary portion of the complex number. Default is 0 (meaning a real number is created).


# Convert the real and imaginary numbers to a complex number.
x = complex(3, 5)
print(f'real component of {x}:      {x.real}')
print(f'imaginary component of {x}: {x.imag}')

# Convert a string to an complex number.
y = complex('6+7j')
print(f'real component of {y}:      {y.real}')
print(f'imaginary component of {y}: {y.imag}')


real component of (3+5j):      3.0
imaginary component of (3+5j): 5.0
real component of (6+7j):      6.0
imaginary component of (6+7j): 7.0


A complex number is a number that can be expressed in the form a + bi, where a and b are real numbers, and i is a symbol called the imaginary unit, and satisfyies the equation i2 = -1. Because no real number satisfies this equation, i was called an imaginary number. For the complex number a + bi, a is called the real part and b is called the imaginary part.

When converting a complex number from a string be sure there are no spaces around the +/-. "5+2j" will convert correctly, but "5 + 2j" will not.

Why j instead of i?

In mathematics, complex numbers are written a + ib. In Python we use j instead of i because

  • It's a convention already used by engineers to avoid confusion with term for electric current (i).
  • i is often (over)used in computing as a loop counter index
  • Guido van Rossum, the man behind Python, has flat out refused to change this citing the issue with i or I looking too much like 1 in source code. We politely disagree.