Type Conversion and Type Casting

In Python you can store numbers, text and booleans into variables without first declaring the type. But at some point you’ll want to move information from one type to another – transforming a string into a number, or a number into a string, for example. That process is known as typecasting.

In this tutorial, you will learn: The difference between implicit and explicit conversion How to use the built-in casting functions in Python The errors that you are likely to encounter along the way

Contents

  • What is Typecasting?
  • Type Conversion – Implicit
  • Type Casting (Explicit Data Type Conversion)
  • Numbers-to-Strings and Back
  • Boolean conversion
  • Converting one collection type to another (list, tuple, set)
  • ord() and chr() — Char-Number Conversion
  • Common Mistakes in Conversion of Types
  • Common Mistakes
  • Best Practices
  • Questions for an Interview
  • Frequently asked questions Summary

What is Type Casting?

Type conversion is changing a value from one data type to another. For example, the string “25” to the integer 25. Python supports two types:

  • Implicit conversion – Python does it for you, without asking you.
  • Explicit conversion (also called type casting) – you do it on purpose, using a built-in function.

Output:

Implicit Type conversion

When Python combines two different numeric types in an expression, it automatically performs an implicit conversion. Python will always convert the ‘smaller’ type to the ‘larger’ type, so that no data is lost.

Output:

Here Python will automatically convert a from int to float before adding, since otherwise combining an int and a float in the same expression would be ambiguous. Note that Python will not automatically convert between unrelated types. Adding an int to a str will cause an error, not a silent conversion from one to the other.

Output:

Type Conversion (Explicit Type Conversion)

Explicit conversion means you call a built-in function to convert a value yourself. This is needed whenever Python cannot (or will not) convert automatically, more often than not with strings.

Output:

Step-by-step explanation:

  • int(“25”) parses the string and returns the integer 25.
  • float ( 100 ) converts the integer 100 to 100.0 .
  • str(5) turns the number 5 into the string “5”.

Converting Numbers to Strings and Back

This is the most common conversion that beginners come across, especially when dealing with user input — input() always returns a str, even if the user types in digits.

Output:

The other way around, combining numbers and text with +, requires converting the number to a string first.

Output:

Converting to Booleans

You can turn any Python value into a bool with the built-in bool(). Most values are “truthy”. There are a few “falsy” values.

Sorry, there isn’t any text provided below. Can you provide the text that you would like to be humanized?

Output:

The Python falsy values are: 0, 0.0, “” (empty string), [], (), {}, None and False. All the other things are true.

Converting between (list, tuple, set) collections

list(), tuple() and set() cast the built-in collection types in Python to each other.

Output:

If you convert a list to a set , any duplicate values will be automatically removed because sets only store unique elements .

ord() and chr() — Character to Number Conversion

Python also allows you to convert between a single character and its underlying Unicode code point.

Output:

Common Mistakes in Type Conversion

Some conversions will not work if the value is not in the proper format. The two most common exceptions are TypeError and ValueError.

Output:

Output:

To convert a decimal string like “3.5” to an integer, convert it to a float, then to an int : int(float(“3.5”)) – which returns 3 ( truncating the decimal part, not rounding ).

Common Mistakes

  • Assuming input() returns a number (it always returns a str, even when it is a number).
  • Trying to directly convert a decimal string with int() — int(“3.5”) raises a ValueError; convert to float first.
  • Forgetting that int() truncates not rounds. int(4.9) == 4 not 5.
  • A TypeError is raised if you try to concatenate a number and string with + without converting.
  • This behavior can be surprising, if not intended, as empty collections are falsy only when explicitly checked – my_list: depends on this behavior.

Best Practices

  • Always put your user input conversions inside a try/except block so you can handle invalid input gracefully.
  • Use float() as an intermediate step to convert decimal strings to int.
  • For code that is easier to read and debug, explicit conversion is preferable over implicit conversion.
  • If you want real rounding instead of truncation use round() instead of int().
  • If you’re unsure of what you’re working with, check a value’s type with type() or isinstance() before converting.

Questions for interview

Q1. What is the difference between implicit and explicit conversion?

Implicit conversion is automatic, done by Python itself (e.g., int to float in a mixed expression). Explicit conversion (or type casting) is done manually by the programmer, using the functions int(), float(), or str().

Q2. Why does int(“3.5”) give an error but int(3.5) does not?

int() can directly truncate a real float value but cannot remove the decimal point from a string form which needs to be first converted to float.

Q3. What does int(4.9) return and why?

It returns 4, because int() truncates the decimal part rather than rounding it.

Q4. What are the falsy values in Python?

0, 0.0, “”, [], (), {}, None and False. Everything else is truthy.

Q5. Why does 5 + “5” result in a TypeError, while 5 + 5.0 is okay?

Python does implicit conversions between compatible numeric types ( int and float ) but str and int are not implicitly compatible as there is no unambiguous numeric or textual meaning to combining them .

FAQs

A: No, converting a list to a set does not preserve order?

No sets are unordered, so the order of the result is not guaranteed to match the order of the original list.

Q: How can I turn a string into a list of characters?

Use list(“hello”) which returns [‘h’, ‘e’, ‘l’, ‘l’, ‘o’] .

Q: What’s the difference between int and round?

Yes, int() truncates towards zero, round() rounds to the nearest whole number (or nearest even number on exact ties).

Q: Can all objects be converted with bool()?

Yes — all Python objects have a Boolean value, either by specific rules for built-in types, or by defining a __bool__ method in user-defined classes.

Summary:

  • Type conversion is converting a value from one data type to another data type. Implicit (done automatically by Python) or explicit (you call a function like int(), float() or str()).
  • input() always returns a string, so you have to explicitly convert numeric input before doing math.
  • Trying to convert an invalid string will raise ValueError . Trying to combine incompatible types will raise TypeError .
  • int() just truncates decimals, it doesn’t round. Use round() if you want proper rounding.
  • Collections like list, tuple, and set can also be cast into one another, which is useful for removing duplicates or changing mutability.