Skip to content

Module 3 · Variables and Data Types — topic 11 of 15

Type casting

Casting converts a value from one type to another on purpose. Learn casting between numbers, strings, Booleans and collections, how to handle failures, and common patterns for user data.

Beginner 12 min read·Lesson 39 of 306 in Python Programming

Learning objectives

  • Cast between numeric, string and collection types
  • Anticipate which casts fail and why
  • Cast safely with validation or try/except

Definition

Casting converts a value from one type to another on purpose. Learn casting between numbers, strings, Booleans and collections, how to handle failures, and common patterns for user data.

Introduction

Type casting is the deliberate conversion of a value to another type using that type’s constructor: int(), float(), str(), bool(), list(), tuple() and set(). Module 2 introduced the basics; here you will see the full range and how to cast safely.

Why it matters

Real data rarely arrives in the type you need. Text from files must become numbers, a string must become a list of characters, a list must become a set to remove duplicates. Knowing what each cast does, and when it fails, prevents crashes.

Detailed explanation

Numeric casts: int(3.99) → 3 (truncates), float(7) → 7.0, int("0042") → 42 (leading zeros are fine in text).

Rounding is not casting: use round(3.99) for 4.

String casts: str(x) works for every value and gives its readable text.

Collection casts: list("abc") → ['a', 'b', 'c']; tuple([1, 2]) → (1, 2); set([1, 1, 2]) → {1, 2}, which removes duplicates.

Failed casts raise ValueError (wrong content, such as int("12a")) or TypeError (impossible type, such as int([1, 2])).

Safe casting means validating the text first or catching the exception and responding helpfully. The try/except form is common and covered fully in Module 12.

Casting to bool deserves special care because it never fails: every value converts to either True or False. That makes it easy to get a wrong answer silently, for example bool("0") is True because the string is not empty. When text represents a yes/no choice, compare it with the expected words instead of casting.

Casting a dictionary with list() gives a list of its keys, and casting a string with list() splits it into single characters rather than words; use split() when you want words.

Syntax

Python
number = int(text)
items = list(iterable)
unique = set(items)
try:
value = float(text)
except ValueError:
value = None
  • Call the target type like a function.
  • Collections can be built from any iterable.
  • Wrap risky casts in try/except ValueError.

Code examples

Number and string casts

Python
print(int("0042"), float(7), str(3.5) + "!")
print(int(3.99), round(3.99))
Output
42 7.0 3.5!
3 4

Collection casts

Python
print(list("abc"))
print(tuple([1, 2, 3]))
print(sorted(set([3, 1, 3, 2, 1])))
Output
['a', 'b', 'c']
(1, 2, 3)
[1, 2, 3]

More examples

Casting a column of messy data

Python
raw = ["12", " 7 ", "3.5", "n/a", "", "40"]
values = []
skipped = []
for item in raw:
try:
values.append(float(item))
except ValueError:
skipped.append(item)
print("values:", values)
print("skipped:", skipped)
print("total:", sum(values))
Output
values: [12.0, 7.0, 3.5, 40.0]
skipped: ['n/a', '']
total: 62.5

Step-by-step explanation

  • raw mimics a spreadsheet column with spaces, a missing value and a text marker.
  • float(item) succeeds for numeric text, even with surrounding spaces.
  • float("n/a") and float("") raise ValueError, so those items are recorded as skipped.
  • The total uses only the successfully cast values.

Expected output

Running “Casting a column of messy data” prints exactly:

TextOutput
values: [12.0, 7.0, 3.5, 40.0]
skipped: ['n/a', '']
total: 62.5

Practical applications

  • Data-cleaning scripts cast CSV columns and log rows that fail.
  • Web forms cast submitted text to numbers and show an error if casting fails.
  • Deduplication of email lists often casts a list to a set.

Best practices

  • Cast as soon as data enters the program.
  • Catch ValueError around casts of untrusted text.
  • Use round() for rounding and int() only for truncation.

Common mistakes

Casting a float string with int()

Avoid

int("4.0")

Prefer

int(float("4.0"))

int() only accepts whole-number text.

Expecting set() to keep order

Avoid

list(set([3, 1, 2])) # order not guaranteed

Prefer

sorted(set([3, 1, 2]))

Sets are unordered; sort the result if order matters.

Key takeaways

  • Casting uses type constructors such as int(), list() and set().
  • Bad content raises ValueError; impossible types raise TypeError.
  • Validate or catch errors when casting user data.

Try it yourself

  1. 1
    Cast the string "hello world" to a set of characters and print how many unique letters it contains (ignore the space).
  2. 2
    Write a loop that asks for numbers until the user enters something that can’t be cast to int, then prints the total.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

12 questions cover the “Variables and Data Types” module. Answers and explanations are revealed after you submit.

  • BeginnerWhat happens after x = 10 and then x = "ten"?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this module