← Back to Python Course | Chapter 1: Basics | Lesson 11 of 14

Python Type Casting

Converting to int

Wrapping a value in int() converts it to a whole number, truncating any decimal part of a float rather than rounding it — int(9.8) gives 9, not 10. Passing a numeric string like int(42) works fine, but int(abc) raises a ValueError since there's no digit sequence to parse.

Example: Converting to int

python
print(int(9.8))
print(int("42"))

Converting to float

float() turns an int or a numeric string into a floating-point number, which is useful whenever you need decimal precision for calculations like averages or percentages. float('3.14') and float(3) both work, but float(three) fails the same way int() does on non-numeric text.

Example: Converting to float

python
print(float("3.14"))
print(float(3))

Converting to str

str() turns any value — a number, a list, a boolean — into its text representation, which is essential whenever you need to concatenate that value into a message with the + operator, since Python won't silently mix strings and numbers. Printing already converts values for you, but explicit str() is needed for manual string building.

Example: Converting to str

python
age = 30
message = "Age: " + str(age)
print(message)

Converting to bool

bool() reduces any value down to True or False using Python's truthiness rules — zero, None, and empty containers become False, and virtually everything else becomes True. This conversion happens automatically inside an if condition, so understanding it explains why if my_list: works without comparing to an explicit length.

Example: Converting to bool

python
print(bool(0))
print(bool([]))
print(bool("hello"))

Converting Between Collections

list(), tuple(), and set() can convert between collection types and other iterables — set() is particularly handy for removing duplicates from a list, since converting to a set drops repeats and converting back to a list restores an ordinary sequence. These conversions build a brand new object rather than modifying the original in place.

Example: Converting Between Collections

python
numbers = [1, 2, 2, 3, 3]
unique = list(set(numbers))
print(unique)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.