Python Complex Numbers

Python Complex Numbers

In Python, complex numbers are used to represent values that combine both real and imaginary parts, making them essential for solving problems in engineering, physics, and advanced mathematics. Python makes it easy to use complex numbers through built-in support and the complex() function. You can create complex numbers using numbers or formatted strings. In this blog, you will understand how to create, use, and work with complex numbers in Python using the complex() function.

Table of Contents:

What are Complex Numbers in Python?

Python complex numbers are a special type of number that contains two parts, which are a real part and an imaginary part. They follow the standard format a + bj, where a is the real component and b is the imaginary component. Complex numbers are commonly used in scientific and technical fields like waveforms, signal processing, electrical circuits, and rotation-based calculations. Python treats them as a separate numeric type with built-in support for arithmetic operations. You can access the real part using the .real attribute and the imaginary part using the .imag attribute.

What is a complex() Function in Python?

The complex() function is a built-in function in Python that is used to construct complex numbers from integers, floats, or strings. It allows you to define both the real and imaginary parts as separate arguments or pass a single string that represents the entire complex value. This function is especially useful when working with dynamic data or converting other data types into a complex form during mathematical operations. It provides an easy and flexible way to create complex numbers in Python.

Here’s what each part means:

  • a is the real part
  • b is the imaginary part
  • j is the imaginary unit, which stands for the square root of -1

In Python, the letter ‘j’ is used instead of ‘i’ (which is more common in standard math notation) to represent imaginary numbers. You can get the real and imaginary parts of a complex number using the .real and .imag attributes.

Syntax of the complex() Function in Python

The complex() function in Python is simple to use and helps create complex numbers. It can take one or two arguments, which can be either numbers or strings representing a complex value, and returns a complex number made up of a real and an imaginary part. If only one argument is passed, it’s treated as the real part, and the imaginary part defaults to 0.

Syntax of complex()

complex([real[, imag]])

Example:

Python

Output:

Syntax of the complex() Function in Python - output

Explanation: Here, “3+4j” is a string that represents a complex number and is directly converted. The second example combines 5 (real part) and 2 (imaginary part) to form 5+2j.

Unlock Python: Power Up Your Programming Skills!
Dive into real-world coding projects and become confident in writing clean, efficient Python code.
quiz-icon

Parameters of the complex() Function in Python

The complex() function accepts two optional parameters, commonly referred to as real and imaginary. These can be numbers or values that are convertible to numbers. You can also pass a single string that represents the full complex number, such as “3+4j”.

1. Real Part (First value or base number)

This is the first value you pass to complex(). It becomes the real part of the complex number. It may be an int, float, or string that represents a complex number.

2. Imaginary Part (Second value or optional imaginary number)

This is the second, optional value that becomes the imaginary part of the complex number.

  • If both real and imaginary are passed, Python creates a complex number like real + imag*j.
  • If only real is passed (for example, “2+3j”), Python parses it into a complex number.
  • If you pass nothing, complex() (again) returns 0j by default.

Return Value of complex() Function in Python

The complex() function returns a complex number in the form a + bj, where a is the real part and b is the imaginary part. When given valid input, such as a number, a pair of numbers, or a properly formatted string like “3+4j” it creates a corresponding complex number.

  • If only one number is provided, the imaginary part is automatically set to 0.
  • When both real and imaginary values are given, they are combined into a full complex number.
  • If no arguments are passed, complex() returns 0j by default.

Working of Python complex() Function with Different Data Types 

The complex() function in Python helps to convert different data types to complex numbers. That includes different data types like integers, floats, and strings. Here are multiple examples of different types of inputs.

1. Using complex() with Integer and Float Values in Python

The complex() function can take integers or float values and convert them into complex numbers. When one value is passed, it becomes the real part, and the imaginary part is automatically set to 0.0. This is mostly useful when you’re looking for advanced mathematical problems or queries.

Example:

Python

Output:

Using complex() with Integer and Float Values in Python - output

Explanation: Here, when the integer 7 and the float 4.5 are provided to the complex() function, it returns complex numbers that only have real parts; that would be 7+0j and 4.5+0j because the imaginary part is assumed to be zero.

2. Using complex() with Strings in Python

The complex() function can take a string and convert it into complex numbers, but the format of the string must be convertible to a complex number (like “3+2j”). It reads both the real and imaginary parts from the string.

Example:

Python

Output:

 Using complex() with Strings in Python output

Explanation: Here, the strings “3+4j” and “-2.5+0j” are in a valid string format, so they can be converted to complex numbers. The complex() function parses them and returns proper complex values. Remember that, if the string is correctly formatted, or else it will raise an error.

Built-in Functions That Support Complex Numbers in Python

Python provides several built-in functions that support and simplify operations on complex numbers. These functions allow developers to calculate magnitudes, raise numbers to powers, check types, and manipulate real and imaginary parts cleanly and effectively.

1. abs()

The abs() function returns the magnitude (or modulus) of a complex number, which is its distance from the origin in the complex plane.

Example:

Python

Output:

abs()  - output

Explanation: Here, abs(z) calculates the magnitude of the complex number 3 + 4j, which is 5.0.

2. pow()

The pow() function in Python allows you to raise a complex number to a specified power. It supports both integer and float exponents for complex base values.

Example:

Python

Output:

pow() – output

Explanation: Here, pow(z, 3) computes (1 + 2j) raised to the power of 3, resulting in (-11+2j).

3. round()

The round() is not directly applicable to complex numbers but can be used separately on the real and imaginary parts.

Example:

Python

Output:

round() -  output

Explanation: Here, both the real and imaginary parts are individually rounded to one decimal place using round().

4. type()

The type() helps to identify the data type of a variable and confirms whether a value is of complex type.

Example:

Python

Output:

type() -  output

Explanation: Here, type(z) shows that the variable z is an instance of the built-in complex type.

5. str() and repr()

Both str() and repr() can be used to get a string version of a complex number. str() is usually for display, while repr() is meant for debugging.

Example:

Python

Output:

str() and repr() - output

Explanation: Here, both str() and repr() return a string form of the complex number. Since complex numbers are neatly formatted by default in Python, both functions output the same.

Get 100% Hike!

Master Most in Demand Skills Now!

Arithmetic Operations with Complex Numbers in Python

In Python, you will be able to perform all the basic arithmetic operations like addition, subtraction, multiplication, and division directly with complex numbers. You can do these operations straightaway, like how you’re doing with normal integers. Here are a few examples that help you to understand how it is working.

1. Addition and Subtraction of Complex Numbers

In Python, you can perform arithmetic operations like addition and subtraction on complex numbers just like you do with regular numbers. When adding or subtracting, Python automatically adds the real parts together and the imaginary parts together.

Example:

Python

Output:

Addition and Subtraction of Complex Numbers - output

Explanation: Here, two complex numbers 3+2j and 1+7j are added and subtracted. Python performs the operations by separately calculating the real parts and the imaginary parts. So 3+1 = 4 and 2+7 = 9 for addition, and 3-1 = 2 and 2-7 = -5 for subtraction.

2. Multiplication and Division of Complex Numbers

In Python, complex numbers follow proper math rules for multiplication and division. When you multiply, Python uses the correct formula to combine the real and imaginary parts. For division, Python handles all the steps and returns the final complex number as the result.

Example:

Python

Output:

Multiplication and Division of Complex Numbers - output

Explanation: Here, Python multiplies 2+3j with 1-1j and also divides them. The multiplication follows the formula: (a+bi)(c+di) = (ac−bd) + (ad+bc)i.

Handling Negative, Zero, and Decimal Values using Complex () in Python

In Python, the complex() function creates numbers with both a real part and an imaginary part. It can take integers, decimal numbers, or zero as input for either part. You can use complex numbers in arithmetic operations like addition, subtraction, multiplication, and division, just as you do with regular numbers. The examples below show how complex numbers work with negative values, zero, and decimals.

1. Using Negative Values with complex()

When you use negative numbers with complex(), Python accepts them without any issue. It simply uses the negative values for the real and imaginary parts to create the complex number.

Example:

Python

Output:

Using Negative Values with complex() -  output

Explanation: Here, the real part of the complex number is -4, and the imaginary part of the complex number is -2, respectively. They are joined to produce complex numbers in Python with ‘negative’ signs  -4-2j.

2. Using Zero in Complex Numbers

In Python, you can set either the real part or the imaginary part of a complex number to zero. Python handles it without any problem, and the result will show only the non-zero part, depending on which one was set to zero.

Example:

Python

Output:

Using Zero in Complex Numbers - output

Explanation: Here, the first number has a zero real part and returns just 6j. The second number has zero imaginary part, so it shows as 9+0j. If both parts are zero, Python gives you 0j.

3. Using Decimal (Float) Values with complex()

In Python, the complex() function is not limited to whole numbers. You can also use it with decimal numbers (floats) to create complex values with more precision.

Example:

Python

Output:

Using Decimal (Float) Values with complex() - output

Explanation: Here, the real part is 2.5 and the imaginary part is -3.75. The complex() function combines them into a decimal-based complex number, making it perfect for calculations that need more accuracy.

Python complex() vs int() and float() Functions

Feature int() Function float() Function complex() Function
Purpose Converts a value to an integer. Converts a value to a floating-point number. Creates a complex number with real and imaginary parts.
Precision Whole numbers only (no decimal or fraction). Approx. 15–17 decimal digits of precision. Handles both real and imaginary parts (standard precision).
Type of Operation Type conversion to an integer. Type conversion to float. Type conversion or creation of complex numbers.
Use Case When only whole numbers are needed. When decimal values are required. When working with real and imaginary numbers together.
Conversion to Other Types Can be cast to float and str. Can be cast to int, str (with loss of precision). Can be cast to str, but not int or float directly.

Common Errors in Python complex() and How to Avoid Them

When using Python’s complex() function, you might face a few common issues, especially with string inputs or unexpected values. Understanding these problems and how to fix them can help you write better and more reliable code. Below are three common errors to watch out for.

1. ValueError: complex() arg is a malformed string

This happens when the string you give to complex() doesn’t follow the format Python expects for complex numbers. Even small things like a space in the wrong place can cause it to fail.

Example:

Python

Output:

ValueError: complex() arg is a malformed string - output

Explanation: Here, in this output, the string “3 + 4j” has spaces, which makes it unreadable to Python’s complex() function.

Solution: Remove all spaces and make sure the string is properly structured.

Corrected Example:

Python

2. TypeError: complex() first argument must be a string or a number, not ‘list’

If you pass in a data type that Python doesn’t expect, like a list or a dictionary, you’ll get this error. complex() only works with numbers or properly formatted strings.

Example:

Python

Output:

 TypeError: complex() first argument must be a string or a number, not 'list' - output

Explanation: Here, Python cannot interpret a list as a valid complex number input.

Solution: Use separate numeric arguments or a valid string to define the complex number.

Corrected Example:

Python

3. ValueError: complex() second arg can’t be a string

This error happens when you try to pass a string as the second argument to complex(). Python only accepts the second value as a number.

Example:

Python

Output:

ValueError: complex() second arg can't be a string - output

Explanation: Here, while 3 is a valid real part, “4” as a string is not accepted for the imaginary part.

Solution:  Make sure both values are either numbers or use a single-string argument if you’re using the “a+bj” format.

Corrected Example:

Python

Best Practices for Working with Python Complex Numbers

The complex() function in Python is easy to use, but following some best practices can help you avoid mistakes. These practices also keep your code clean and easier for others to understand.

  1. Prefer complex() over direct notation: Use the complex() function instead of writing numbers like 3+4j to keep your code clean and readable.
  2. Use only numbers as inputs: Always pass integers or floats; strings, lists, or other types will cause an error.
  3. Access parts with .real and .imag: To get the real or imaginary part, use .real or .imag directly instead of splitting manually.
  4. Avoid unnecessary use: Only use complex numbers when your logic truly needs them, especially for math or engineering tasks.
  5. Validate input types before use: Always check or convert input types before passing them to avoid runtime errors.
Master Python Basics – 100% Free Learning Path!
Explore variables, loops, functions, and more with free Python tutorials designed for beginners.
quiz-icon

Conclusion

Complex numbers in Python offer a powerful way to handle calculations that go beyond real numbers. Using the complex() function, you can easily represent and work with values that have both real and imaginary parts. This is especially useful in fields like engineering, physics, and advanced mathematics. By understanding how to use complex numbers effectively, you can expand your problem-solving skills and write more flexible, math-ready code.

Take your skills to the next level by enrolling in the Python Course today and gaining hands-on experience. Also, prepare for job interviews with Python Interview Questions designed by industry experts.

Python Complex Numbers – FAQs

Q1. What does the complex() function do in Python?

The complex() function creates a complex number by combining a real part and an imaginary part. It can also turn a properly formatted string like “3+4j” into a complex number.

Q2. Can I use complex() with just one number?

Yes. If you give it one number, Python treats it as the real part, and the imaginary part becomes 0 by default. For example, complex(5) becomes (5+0j).

3. What kind of input can I pass into complex()?

You can pass integers, floats, or a string that looks like a complex number (like “2+3j”). If you’re passing two numbers, the first is the real part and the second is the imaginary part.

4. What happens if I pass a non-numeric string to complex()?

You’ll get a ValueError. For example, complex(“hello”) will throw an error, because it’s not a valid number format.

5. Can I do math with complex numbers in Python?

Absolutely. You can add, subtract, multiply, and divide complex numbers using regular operators like +, -, *, and /.

About the Author

Senior Associate - Digital Marketing

Shailesh is a Senior Editor in Digital Marketing with a passion for storytelling. His expertise lies in crafting compelling brand stories; he blends his expertise in marketing with a love for words to captivate audiences worldwide. His projects focus on innovative digital marketing ideas with strategic thought and accuracy.

Advanced Data Science AI