Skip to content

Type Conversion

"Practicality beats purity."
— The Zen of Python

Introduction

Type conversion is the process of converting one data type into another.

Python provides several built-in functions for converting between common data types.

Type conversion appears frequently in coding interviews, especially when working with user input, strings, numbers, lists, sets, and dictionaries.


Implicit Type Conversion

Python automatically converts compatible types when it is safe to do so.

result = 10 + 2.5

print(result)

Output

12.5

Python automatically converts the integer into a float.


Explicit Type Conversion

Explicit conversion is performed using built-in functions.

Example

age = "25"

age = int(age)

int()

Converts a compatible value into an integer.

int("42")

Output

42

int(3.9)

Output

3

Notice that it truncates the decimal part instead of rounding.


Invalid conversion

int("abc")

Raises

ValueError

Common Interview Use Cases

Convert user input

n = int(input())

Convert digits while iterating over a string

digit = int(ch)

float()

Converts a value into a floating-point number.

float("3.14")

Output

3.14

str()

Converts any object into its string representation.

str(123)

Output

"123"

Useful when building output strings.


list()

Creates a list from an iterable.

list("hello")

Output

['h', 'e', 'l', 'l', 'o']

Common interview trick

chars = list(s)

chars.reverse()

result = "".join(chars)

tuple()

Creates a tuple.

tuple([1, 2, 3])

Output

(1, 2, 3)

set()

Creates a set.

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

Output

{1, 2, 3}

Very common for removing duplicates.


Interview example

if len(nums) != len(set(nums)):
    print("Duplicates Found")

dict()

Creates a dictionary.

pairs = [
    ("a", 1),
    ("b", 2)
]

dictionary = dict(pairs)

Output

{
    "a": 1,
    "b": 2
}

bool()

Converts values into boolean form.

bool(1)

Output

True

bool(0)

Output

False

bool("")

Output

False

bool("Python")

Output

True

ord()

Returns the Unicode code point of a character.

ord("a")

Output

97

Very useful in string problems.

Example

index = ord(ch) - ord("a")

We'll cover this in detail in the Strings section.


chr()

Converts a Unicode value back into a character.

chr(97)

Output

'a'

Binary, Octal and Hexadecimal

Convert to binary

bin(10)

Output

'0b1010'

Convert to hexadecimal

hex(255)

Output

'0xff'

Convert to octal

oct(10)

Output

'0o12'

Parsing Different Bases

Binary

int("1010", 2)

Output

10

Hexadecimal

int("FF", 16)

Output

255

Common Interview Examples

Reverse Integer

num = int(str(num)[::-1])

Remove Duplicate Characters

unique = set(s)

Convert String to Character List

chars = list(word)

Frequency Array

index = ord(ch) - ord("a")

Time Complexity

Operation Complexity
int() O(n) (for strings)
float() O(n)
str() O(n)
list() O(n)
tuple() O(n)
set() O(n)
dict() O(n)
bool() O(1)
ord() O(1)
chr() O(1)

Common Mistakes

Mistake 1

Using

int("3.14")

Raises

ValueError

Instead

int(float("3.14"))

Mistake 2

Expecting

list(123)

to work.

It raises

TypeError

Only iterables can be converted using list().


Mistake 3

Assuming

bool("False")

returns False.

It returns

True

Any non-empty string is truthy.


Best Practices

  • Use set() to remove duplicates.
  • Use list() when string mutation is required.
  • Use ord() and chr() for character arithmetic.
  • Avoid unnecessary conversions inside loops.
  • Validate user input before conversion.

Key Takeaways

  • Python provides built-in functions for converting between common data types.
  • ord() and chr() are extremely useful for string algorithms.
  • set() is one of the easiest ways to remove duplicates.
  • Be aware that some conversions may raise exceptions.
  • Avoid repeated conversions inside performance-critical loops.

  • Truthy and Falsy Values
  • Strings
  • Sets
  • Dictionaries
  • ASCII and Unicode

Practice Questions

  1. What is the difference between implicit and explicit conversion?
  2. Why does int(3.9) return 3?
  3. What does list("hello") produce?
  4. How do you remove duplicates using set()?
  5. Why is ord() useful in interview questions?

Summary

Type conversion is a fundamental skill for Python programmers.

Understanding when and how to convert between data types allows you to write cleaner, more efficient solutions and makes many interview problems significantly easier to solve.

The next chapter introduces the operators that appear most frequently in coding interviews, including arithmetic, comparison, logical, membership, identity, and bitwise operators.