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 Python complex numbers.
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 Python complex number that is 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:
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.
Parameters of the complex() Function in Python
This 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 a 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 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
This Python function helps to convert different data types to Python 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:
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 Python 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:
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 Python Complex Numbers
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() Function in Python
The abs() Function in Python returns the magnitude (or modulus) of a complex number, which is its distance from the origin in the complex plane.
Example:
Output:
Explanation: Here, abs(z) calculates the magnitude of the complex number 3 + 4j, which is 5.0.
2. pow() Function in Python
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:
Output:
Explanation: Here, pow(z, 3) computes (1 + 2j) raised to the power of 3, resulting in (-11+2j).
3. round() Function in Python
The round() function in Python is not directly applicable to complex numbers, but can be used separately on the real and imaginary parts.
Example:
Output:
Explanation: Here, both the real and imaginary parts are individually rounded to one decimal place using round().
4. type() Function in Python
The type() function in Python helps to identify the data type of a variable and confirms whether a value is of complex type.
Example:
Output:
Explanation: Here, type(z) shows that the variable z is an instance of the built-in complex type.
5. str() and repr() Functions in Python
Both str() and repr() functions in Python can be used to get a string version of a complex number. str() is usually for display, while repr() is meant for debugging.
Example:
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.
When to Use complex() Over int() or float() in Python?
Python provides three primary numeric types:
int
: For whole numbers like 5
, -3
, 0
float
: For decimal numbers like 3.14
, -0.001
, 2.0
complex
: For numbers with both real and imaginary parts, like 3+4j
Use complex() only when you’re dealing with data that requires imaginary components. You do not use int() or float() for imaginary numbers; these types only support real values.
When to Use Each:
Function |
Use Case |
int() |
When the number has no decimal or imaginary part |
float() |
When you need real numbers with decimals |
complex() |
When dealing with both real and imaginary components |
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 works.
1. Addition and Subtraction of Python 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: Here, let’s see how to add two complex numbers using Python:
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 Python 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:
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.
Alternative Method to Initialize Complex Numbers in Python
While complex() is the most flexible and explicit way to create complex numbers, Python also allows you to use direct notation using the j suffix.
Example:
Output:
Explanation: Here, this defines two complex numbers using variables with 1j, then performs multiplication and division between them. It prints the original numbers and the results of the arithmetic operations.
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.
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:
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:
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:
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:
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:
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:
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.
- Prefer complex() over direct notation: Use the complex() function instead of writing numbers like 3+4j to keep your code clean and readable.
- Use only numbers as inputs: Always pass integers or floats; strings, lists, or other types will cause an error.
- Access parts with .real and .imag: To get the real or imaginary part, use .real or .imag directly instead of splitting manually.
- Avoid unnecessary use: Only use complex numbers when your logic truly needs them, especially for math or engineering tasks.
- 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.
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 Python 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.
Check out our other blogs related to Python functions:
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. How to Use Complex Numbers in Python?
You can use complex numbers in Python by creating them with the complex() function or using the j notation, like a = 3 + 4j.
Q3. 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.
Q4. 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.
Q5. Can I do math with complex numbers in Python?
Absolutely. You can add, subtract, multiply, and divide complex numbers using regular operators like +, -, *, and /.