Skip to Content
Type Conversion

Type Conversion

Type conversion (casting) transforms a value from one type to another. Explicit conversion uses built-ins such as str(), int(), float(), bool(), list(), tuple(), and set(). Understanding conversion rules and edge cases avoids subtle bugs.

Built-in Conversions

FunctionConverts toTypical input types
str(x)StringAny type
int(x)Integerstr, float, bool
float(x)Floatstr, int, bool
bool(x)BooleanAny type (truthiness)
list(x)Listiterable (str, tuple, set, range)
tuple(x)Tupleiterable (list, str, set, range)
set(x)Setiterable (list, str, tuple)

str() Conversion

From any type: Produces a string representation of the value. Every built-in type supports this.

str(66) # "66" str(82.6) # "82.6" str(True) # "True" str([2, 4]) # "[2, 4]" str(None) # "None"

Numeric precision: str() uses a default representation. For controlled formatting (e.g. fixed decimal places), use f-strings or format().

str(2.468) # "2.468" f"{2.468:.2f}" # "2.47"

Iterables (list, tuple, set): str() works with iterables too. It converts the whole object to one string; it does not iterate over the elements.

str([1, 2, 3]) # "[1, 2, 3]" str((1, 2)) # "(1, 2)" str({1, 2, 3}) # "{1, 2, 3}" - order may vary

int() Conversion

From string: Parses a string as an integer. Leading and trailing whitespace is ignored. The string must represent a valid integer literal.

int("222") # 222 int(" 42 ") # 42 int("-8") # -8

From float: Truncates toward zero. The fractional part is discarded.

int(82.6) # 82 int(82.2) # 82 int(-4.8) # -4

From bool: True → 1, False → 0.

int(True) # 1 int(False) # 0

Base parameter: int(s, base) parses a string in the given base (2–36).

int("10", 2) # 2 (binary) int("24", 8) # 20 (octal) int("2A", 16) # 42 (hexadecimal)

Invalid input: Non-numeric strings raise ValueError.

# int("abc") # ValueError # int("42.6") # ValueError - use float() first

Float then int: To convert a numeric string with a decimal point, use float() first, then int().

int(float("82.6")) # 82

float() Conversion

From string: Parses a string as a floating-point number. Accepts integers and decimals.

float("82.6") # 82.6 float("42") # 42.0 float("-2.4") # -2.4 float(" 6.8 ") # 6.8

From int: Produces a float with a decimal part of zero.

float(66) # 66.0 float(-4) # -4.0

From bool: True → 1.0, False → 0.0.

float(True) # 1.0 float(False) # 0.0

Special strings: "inf", "-inf", "nan" produce special float values.

float("inf") # inf float("nan") # nan

Invalid input: Non-numeric strings raise ValueError.

# float("abc") # ValueError

bool() Conversion

Truthiness: bool(x) returns False for “falsy” values and True otherwise. Falsy values include None, 0, 0.0, "", [], (), {}, and set().

bool(0) # False bool(1) # True bool("") # False bool("hi") # True bool([]) # False bool([2, 4]) # True bool(None) # False

Numeric zero: Only zero is falsy; any non-zero number is truthy.

bool(-1) # True bool(0.0) # False

list() Conversion

From iterable: Builds a new list from any iterable. Order is preserved.

list("abc") # ['a', 'b', 'c'] list((1, 2, 3)) # [1, 2, 3] list(range(3)) # [0, 1, 2] list({2, 4, 6}) # [2, 4, 6] - order not guaranteed

From dict: list(d) gives the keys. Use list(d.items()) for key–value pairs.

list({"a": 1, "b": 2}) # ['a', 'b'] list({"a": 1, "b": 2}.items()) # [('a', 1), ('b', 2)]

tuple() Conversion

From iterable: Builds a new tuple from any iterable. Immutable and hashable (if elements are hashable).

tuple([1, 2, 3]) # (1, 2, 3) tuple("ab") # ('a', 'b') tuple(range(2)) # (0, 1) tuple({2, 4}) # (2, 4) - order not guaranteed

From dict: tuple(d) gives the keys, same as list(d) but as a tuple.

set() Conversion

From iterable: Builds a set of unique elements. Duplicates are removed; order is not preserved.

set([1, 2, 2, 3]) # {1, 2, 3} set("hello") # {'h', 'e', 'l', 'o'} set((1, 1, 2)) # {1, 2}

From dict: set(d) gives the keys. Values are ignored.

set({"a": 1, "b": 2}) # {'a', 'b'}

Note: Set elements must be hashable. set([[1], [2]]) raises TypeError because lists are not hashable.

Common Casting Patterns

String → int: int("222") → 222.

Float → int: int(82.6) → 82 (truncation).

Int → float: float(66) → 66.0.

Any → string: str(x) for any x.

Iterable → list / tuple / set: list(iterable), tuple(iterable), set(iterable) - use set() when you need unique elements and do not care about order.

Truthiness check: bool(x) to get an explicit True/False from any value.

Exercise pattern: Given DATA = ["222", 82.6, 66], cast each element to its natural type:

DATA = ["222", 82.6, 66] def cast(): return (int(DATA[0]), float(DATA[1]), str(DATA[2])) # (222, 82.6, "66")

Implicit vs Explicit Conversion

Explicit: Using int(), float(), str(), bool(), list(), tuple(), set() - clear and controlled.

Implicit: Python converts automatically in some contexts (e.g. 2 + 4.0 → 6.0). Relying on implicit conversion can obscure intent; explicit casting is often clearer.

Tricky Behaviors

str() and repr()

str(x) aims for readability; repr(x) aims for an unambiguous representation. For many types they differ: str("hi")"hi", repr("hi")"'hi'".

Truncation vs rounding

int(8.6) truncates to 8; it does not round. Use round(8.6) for rounding, then int() if needed.

Float precision

Floats use binary representation; some decimals cannot be stored exactly. 0.1 + 0.2 may not equal 0.3 exactly. For financial or exact decimal math, consider decimal.Decimal.

Empty string

int("") and float("") raise ValueError. Check for empty strings before converting if input may be empty.

Boolean as numeric

int(True) is 1 and int(False) is 0. This can be useful but may surprise those from languages where booleans are not numeric.

set() removes duplicates and loses order

set([1, 2, 2, 3]) yields {1, 2, 3}. Do not rely on element order; use list() or tuple() when order matters.

Interview Questions

Does str() work on all types?

Yes. Every object has a string representation. Custom classes can override __str__ to control it.

What does int(82.6) return?

  1. int() truncates toward zero; it does not round.

How do you convert “42.8” to an integer?

int(float("42.8")) - int() cannot parse strings with decimal points directly.

What is the difference between int() and round()?

int() truncates; round() rounds to the nearest integer. int(4.8) → 4, round(4.8) → 5.

When does int(“x”) raise an error?

When the string does not represent a valid integer. ValueError is raised for non-numeric strings or strings with decimal points.

What does set() do to duplicates?

It removes them. set([1, 1, 2, 2]) returns {1, 2}. The result is unordered.

When would you use list() vs tuple() for conversion?

Use list() when you need a mutable sequence (e.g. to append or sort). Use tuple() when you need an immutable, hashable sequence (e.g. as a dict key or set element).

Last updated on