# What Are Complex Data Type in Python?

//

Larry Thompson

In Python, complex data types are used to represent complex numbers. A complex number is a number that consists of a real part and an imaginary part. It is written in the form `a + bj`, where a is the real part and b is the imaginary part multiplied by the imaginary unit j.

## Creating Complex Numbers in Python

To create a complex number in Python, you can use the built-in function complex(). It takes two arguments: the real part and the imaginary part.

“`python
# Creating a complex number
z = complex(3, 4)
print(z) # Output: (3+4j)
“`

You can also create a complex number using literals by adding a lowercase ‘j’ suffix to the imaginary part.

“`python
# Creating a complex number using literals
z = 3 + 4j
print(z) # Output: (3+4j)
“`

## Accessing Real and Imaginary Parts

To access the real and imaginary parts of a complex number, you can use the dot notation with attributes ‘real’ and ‘imag’.

“`python
# Accessing real and imaginary parts
z = 3 + 4j
print(z.real) # Output: 3.0
print(z.imag) # Output: 4.0
“`

## Performing Operations on Complex Numbers

You can perform various operations on complex numbers in Python, including addition, subtraction, multiplication, division, and more.

• Addition: To add two complex numbers, you can simply use the + operator.
• Subtraction: To subtract one complex number from another, you can use the operator.
• Multiplication: To multiply two complex numbers, you can use the * operator.
• Division: To divide one complex number by another, you can use the / operator.

Here’s an example that demonstrates these operations:

“`python
# Performing operations on complex numbers
z1 = 3 + 4j
z2 = 2 + 5j

print(z1 + z2) # Output: (5+9j)

# Subtraction
print(z1 – z2) # Output: (1-1j)

# Multiplication
print(z1 * z2) # Output: (-14+23j)

# Division
print(z1 / z2) # Output: (0.8620689655172413-0.034482758620689655j)
“`

## Conclusion

In Python, complex data types allow us to work with complex numbers easily. You can create complex numbers using either the complex() function or by using literals with a lowercase ‘j’ suffix.

Accessing real and imaginary parts is straightforward using the dot notation. Additionally, Python provides various operators to perform arithmetic operations on complex numbers.

Complex numbers are widely used in mathematical and scientific computations, so understanding how to work with them in Python can be beneficial for solving complex problems.