Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Convert Binary tuple to Integer
Next article icon

Python Complex to Int

Last Updated : 19 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, we can work by changing the data types of objects using type conversion or typecasting. Type conversion in Python is of two types - Implicit, where type conversion is automatically performed by Python, and explicit, where we make use of predefined functions to change data types. In this post, we will learn how we can convert a Complex data type to Int in Python, if at all.

Complex Data Type to Int in Python

Note that a complex number has two parts, real and imaginary. We can make use of the real and imag attributes of Python to access the real and imaginary part of a complex data type as float respectively.

Python3
#complex data type x = 4 + 6j  #access the real part of the data  print(x.real)  #access the imaginary part of the data print(x.imag) 

Output
4.0 6.0 

Thus, we will first use the real attribute to change the complex number to a float and then further use the int() function to convert the float data type to an integer. Here is the code for the same:

Python3
#complex data type x = 4 + 6j  #the given complex number  print("The given complex number: ", x)   #access the real part of the data and store it in a new variable  r = x.real  #change the float to int  i = int(r)   #the equivalent integer print("The equivalent integer: ", i)  

Output
The given complex number:  (4+6j) The equivalent integer:  4 

Error While Converting Python Complex to Int

To convert a complex number into an integer, we can use the same method of explicit type conversion. However, there is a problem. Look at the code given below.

Here, we are changing an integer data type to a complex data type using the complex() function which works normally as expected.

Python3
# x contains an integer value x = 4  # print the integer print(x)  # print the value of x after type casting it to a complex data type print(complex(x)) 

Output
4 (4+0j) 

However, if we try the opposite of this, that is, if we use the int() data type to change a complex data type to an integer, then we will run into an error:

Python3
#x contains a complex value   x = 4 + 3j   #print the complex number print(x)  #print the value of x after type casting it to an int data type  print(int(x)) 

Output

Traceback (most recent call last):

File "Solution.py", line 8, in <module>

print(int(x))

TypeError: can't convert complex to int

This happens because we cannot convert a larger data type to a smaller data type since it leads to the loss of data. Naturally, changing a complex to integer will result in the loss of the imaginary part of the number, and thus, this kind of type casting is not supported by Python. The same is true for some other data types as well. As an example, we cannot convert a string to an integer in Python using the int() function. Here is the code for the same:

Python
#string data type x = &quot;GFG&quot;  #type cast string to int  print(int(x)) 

Output

Traceback (most recent call last):

File "Solution.py", line 5, in <module>

print(int(x))

ValueError: invalid literal for int() with base 10: 'GFG'

Thus, we can say that conversion of a complex to integer is not possible in Python. However, if you do not care about the loss of the imaginary part of a complex number, then you can follow some workarounds to get the desired result.

This is essentially how you can convert a complex number to an Integer in Python. Note that there is loss of data even if you follow this workaround, and hence, you should only use this when absolutely necessary.


Next Article
Python - Convert Binary tuple to Integer

E

everythingtech
Improve
Article Tags :
  • Python Programs
  • Geeks Premier League
  • Geeks Premier League 2023

Similar Reads

  • .to_bytes() in Python
    In Python, the .to_bytes() method is used to convert an integer into its byte representation. This is useful when weneed to store or transmit data in binary format. Example: Convert the integer 10 into bytes[GFGTABS] Python num = 10 byte_data = num.to_bytes(2, 'big') print(byte_data) [/GFGTA
    2 min read
  • Python | Convert Tuple to integer
    Sometimes, while working with records, we can have a problem in which we need to convert the data records to integer by joining them. Let's discuss certain ways in which this task can be performed. Method #1 : Using reduce() + lambda The combination of above functions can be used to perform this tas
    5 min read
  • Python - Ways to convert hex into binary
    We are given a hexadecimal number we need to convert it to binary. For example a = "1A3" we need to convert it to binary so that resultant output should be 110100011. Using bin() and int()We can convert hexadecimal to binary by first converting it to an integer using int() and then using the bin() f
    1 min read
  • Convert Floating to Binary - Python
    The task of converting a floating-point number to its binary representation in Python involves representing the number in the IEEE 754 format, which consists of a sign bit, an exponent and a mantissa. For example, given the floating-point number 10.75, its IEEE 754 32-bit binary representation is "0
    3 min read
  • Python - Convert Binary tuple to Integer
    Given Binary Tuple representing binary representation of a number, convert to integer. Input : test_tup = (1, 1, 0) Output : 6 Explanation : 4 + 2 = 6. Input : test_tup = (1, 1, 1) Output : 7 Explanation : 4 + 2 + 1 = 7. Method #1 : Using join() + list comprehension + int() In this, we concatenate t
    5 min read
  • Python - Convert Float to digit list
    We are given a floating-point number and our task is to convert it into a list of its individual digits, ignoring the decimal point. For example, if the input is 45.67, the output should be [4, 5, 6, 7]. Using string manipulationIn this method, the number is converted to a string and then each chara
    4 min read
  • Convert list to Python array - Python
    We can use a number of approaches to convert a list into a Python array based on the requirements. One option is to use the array module, which allows us to create arrays with a specified data type. Another option is to use the numpy.array() method, which provides more features for working with arra
    2 min read
  • How to get two decimal places in Python
    In Python programming, while working on financial calculations, a need to round a value to two decimal places may arise. Handling this precision of float-point values is quite easy as there are many ways to do that. Let's explore a simple example to get two decimal places in Python. [GFGTABS] Python
    3 min read
  • Python - Convert None to empty string
    In Python, it's common to encounter None values in variables or expressions. In this article, we will explore various methods to convert None into an empty string. Using Ternary Conditional OperatorThe ternary conditional operator in Python provides a concise way to perform conditional operations wi
    2 min read
  • Python - Binary list to integer
    A binary list represents binary digits (0s and 1s) as individual elements of a list. This article will explore various methods to convert a binary list into an integer. Using int() with String ConversionThis is the most efficient method. By joining the binary list into a string and using the built-i
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences