Type conversion python
Understanding Type Conversion in Python
In Python, you often encounter situations where you need to convert data from one type to another. For example, you might want to convert an immutable tuple into a list so you can modify it. Python provides simple and powerful mechanisms to handle such conversions.
Types of Type Conversion
There are two ways to perform type conversion in Python:
-
Implicit Type Conversion — Done automatically by Python.
-
Explicit Type Conversion — Done manually by the programmer using built-in functions.
Implicit Type Conversion
Python automatically performs type conversion when needed to avoid data loss during operations involving mixed types.
Example:
-
When adding an int and a float, Python promotes the integer to a float.
-
When adding an int and a bool, Python treats True as
1and False as0.
Explicit Type Conversion
You can explicitly convert data from one type to another using built-in functions like:
-
int() -
float() -
str() -
list() -
tuple() -
set()
Example:
If you attempt to perform arithmetic between incompatible types (e.g. int + str) without conversion, Python will raise an error.
Converting Between Container Types
You can easily convert between lists, tuples, and sets:
-
list() and tuple() preserve order.
-
set() removes duplicates and does not preserve order.
String Representation of Containers
You can convert containers and numbers into strings using str():
👀Note that string concatenation using + will combine the strings rather than performing numeric addition.
Converting Containers to Lists
You can convert tuples and sets into lists:
-
Tuples maintain order.
-
Sets are unordered, so the resulting list order may vary.
Binary, Octal, and Hexadecimal Conversions
Python makes it easy to convert integers to binary, octal, or hexadecimal:
Prefixes indicate the number system:
-
0b→ binary -
0x→ hexadecimal -
0o→ octal
Converting Back to Decimal
To convert binary, octal, or hexadecimal strings back to decimal:
Use int() with the appropriate base as the second argument.
Summary
-
Implicit conversion is automatic and seamless.
-
Explicit conversion uses functions like
int(),float(),str(), etc. -
You can convert between container types (lists, tuples, sets) and between numeric bases (binary, octal, hex, decimal).
-
str()is very useful for debugging and preparing data for display.