Type Conversion
Type conversion (or type casting) is the process of converting a value from one
data type to another. Python provides built-in functions like int(), float(),
str(), and bool() for this purpose.
Basic Type Conversions
Python provides several built-in functions to convert between basic types:
| Function | Converts To | Example |
|---|---|---|
int() | Integer | int("42") → 42 |
float() | Float | float("3.14") → 3.14 |
str() | String | str(42) → "42" |
bool() | Boolean | bool(1) → True |
type() | N/A | Returns the type of a value |
Click Run to execute your code
int() truncates toward zero - it doesn't round!
int(3.9) gives 3, not 4. Use round() if you need rounding.
Numeric Type Conversions
Python has three numeric types: int, float, and complex.
Understanding how they convert between each other is crucial.
Click Run to execute your code
int → float → complex. This is called implicit type coercion.
String Conversions
Converting to and from strings is one of the most common operations, especially when dealing with user input or file data.
Click Run to execute your code
int("3.14") raises ValueError. Use int(float("3.14")) instead.
Collection Type Conversions
Python's collection types (list, tuple, set, dict)
can be converted between each other.
| Function | Creates | Key Behavior |
|---|---|---|
list() | List | Mutable, ordered sequence |
tuple() | Tuple | Immutable, ordered sequence |
set() | Set | Unique values only, unordered |
dict() | Dictionary | From key-value pairs |
Click Run to execute your code
set() to easily remove duplicates from a list:
unique = list(set(my_list)). Note: order may not be preserved!
Common Mistakes
1. Converting non-numeric strings to int/float
# This raises ValueError!
int("hello") # ValueError
float("abc") # ValueError
# Always validate before converting
user_input = "42"
if user_input.isdigit():
number = int(user_input)
2. Expecting int() to round
# int() truncates, doesn't round!
int(2.9) # 2, not 3
int(-2.9) # -2, not -3
# Use round() for rounding
round(2.9) # 3
round(2.5) # 2 (banker's rounding!)
round(3.5) # 4
3. Thinking bool("False") is False
# Any non-empty string is truthy!
bool("False") # True! (non-empty string)
bool("") # False (empty string)
# For string "False" to False
text = "False"
result = text.lower() == "true" # False
4. Losing precision with float-to-string
# str() may not show all decimal places
pi = 3.141592653589793
print(str(pi)) # '3.141592653589793'
# Use formatting for control
print(f"{pi:.2f}") # '3.14'
print(f"{pi:.10f}") # '3.1415926536'
Exercise: Type Conversion Practice
Task: Practice converting between Python's different data types.
Skills tested:
- Basic type conversions (int, float, str, bool)
- Collection conversions (list, tuple, set, dict)
- Character conversions (ord, chr)
- Chained conversions
Click Run to execute your code
Show Solution
string_number = "123"
float_number = 45.67
mixed_list = [1, 2, 2, 3, 3, 3, 4]
text = "Python"
pairs = [("name", "Alice"), ("age", "25")]
# 1. String to int, add 10
print(int(string_number) + 10) # 133
# 2. Float to int (truncate)
print(int(float_number)) # 45
# 3. Float to string with 1 decimal
print(f"{float_number:.1f}") # '45.7'
# 4. Remove duplicates
print(list(set(mixed_list))) # [1, 2, 3, 4]
# 5. String to list of chars
print(list(text)) # ['P', 'y', 't', 'h', 'o', 'n']
# 6. Pairs to dictionary
print(dict(pairs)) # {'name': 'Alice', 'age': '25'}
# 7. ASCII value of first char
print(ord(text[0])) # 80
# 8. Boolean to int
print(int(10 > 5)) # 1
# 9. List of ASCII to string
print(''.join(chr(n) for n in [72, 105, 33])) # 'Hi!'
# 10. String → int → add → string
print(str(int("42") + 8)) # '50'
Summary
- int(): Convert to integer (truncates floats)
- float(): Convert to floating-point number
- str(): Convert to string representation
- bool(): Convert to boolean (falsy values → False)
- list(), tuple(), set(): Convert sequences
- dict(): Create dictionary from key-value pairs
- ord(), chr(): Character ↔ ASCII/Unicode conversion
- Implicit coercion: Python auto-converts in operations (int → float → complex)
What's Next?
In the next lesson, we'll explore None - Python's special null value that represents the absence of a value.
Enjoying these tutorials?