PythonPython Variables and Data TypesPython data types

What is type conversion in Python?

Question 37 of 88 · Updated

On this page

Type conversion is the process of obtaining a value of one data type from a value of another type. Python supports implicit conversion in compatible operations and explicit conversion using constructors or conversion functions such as int(), float(), str(), bool(), list() and tuple().

For example, converting the string "42" to an integer lets you use its numerical value in arithmetic. The original string is not changed; the conversion produces a result that can be bound to a name.

1. Why type conversion is needed#

Applications frequently receive data in a different representation from the one required for processing. A form may supply quantities as text, a file may contain encoded bytes, and a calculation may combine integers and floating-point values.

The purpose of conversion is to represent data in a form that supports the intended operation. Conversion does not necessarily preserve all information, and not every source value can be converted to every target type.

SourceOperationResult
"42"int("42")Integer 42
"3.5"float("3.5")Float 3.5
42str(42)String "42"
-3.9int(-3.9)Integer -3
0bool(0)False
"ab"list("ab")List ['a', 'b']

Python is dynamically typed. A name can be rebound to the converted result, but this does not mean the original object has changed its type.

2. Implicit and explicit type conversion#

Python's built-in numeric operations can perform implicit conversions when operands have compatible types. Explicit conversion is initiated by calling a constructor or another conversion operation.

Loading diagram…

The diagram represents common conversions rather than a universal implementation algorithm. Implicit operations can also fail or lose precision; explicit conversions can return an existing object if the target representation permits it.

Implicit conversion#

PYTHON
result = 2 + 0.5 print(result, type(result).__name__) print(type(2 + 3j).__name__)

Output:

2.5 float
complex

For these built-in operations, the real integer operand participates in floating-point or complex arithmetic as appropriate. Python follows the applicable numeric operation's rules rather than a general rule that all operands can be freely converted.

Python does not automatically parse arbitrary strings as numbers during arithmetic. For instance, 2 + "3" raises TypeError. Mixed-type comparisons also have their own semantics; do not assume Python always converts an integer to float before checking numerical equality.

Explicit conversion#

PYTHON
print(int(' +42 '), float('3.5'), int(-3.9))

Output:

42 3.5 -3

Here the programmer deliberately requests an integer or floating-point representation. The int constructor can parse a supported integer string or truncate a finite float toward zero. Those are different conversion contracts; int("3.5") does not work merely because int(3.5) works.

3. Common explicit conversion functions#

Function or constructorCommon useImportant limitation
int(value)Whole numbers or integer-form textTruncates finite floats toward zero; rejects decimal-point strings
float(value)Floating-point numbers or numeric textCan round exact values; accepts some non-finite spellings
complex(value)Complex numbersComponents have finite precision
str(value)Text representationNot necessarily a reversible serialization
bool(value)Truth-value testingDoes not interpret arbitrary text as logical vocabulary
list(iterable)Materialize iterable elements into a listConsumes iterables; nested objects may be shared
tuple(iterable)Construct an immutable sequenceDoes not recursively freeze objects
set(iterable)Collect unique hashable elementsRemoves duplicates and does not preserve sequence order
dict(source)Construct a mappingKeys must be hashable
bytes(source)Construct binary dataText requires explicit encoding

These functions have more than one accepted input form in some cases. Always check the target type's contract rather than assuming conversion has a single meaning.

4. Converting between numeric types and text#

The integer constructor accepts an optional base when parsing text.

PYTHON
print(int('101', 2), int('0xff', 0), str(42))

Output:

5 255 42

The first string is interpreted as binary. Base zero recognizes supported base prefixes such as 0xff for hexadecimal. The str call produces the ordinary text representation of an integer.

A string containing a decimal point is not an integer-form string. Avoid using int(float(text)) as a universal workaround: it can discard a fractional part and introduce floating-point precision loss before the integer conversion.

Use int directly when the input must be an integer string. Use float when an approximate floating-point value is desired. If the application requires exact decimal quantities, consider Decimal constructed from decimal text.

5. Boolean conversion is truth testing#

PYTHON
print(bool('False'), bool(''), bool(0))

Output:

True False False

The bool constructor evaluates the truth value of the object. It does not interpret the English word "False" as the Boolean False. Nonempty ordinary strings are truthy.

When reading textual flags from a configuration file or environment variable, define which values are accepted and parse them explicitly. The earlier Boolean lesson provides a complete example of a strict text-flag parser.

6. Converting collections#

PYTHON
print(list('ab')) print(tuple([1, 2])) print(sorted(set([2, 1, 2]))) print(dict([('a', 1)]))

Output:

['a', 'b']
(1, 2)
[1, 2]
{'a': 1}

Each conversion follows a different contract. The list constructor consumes the characters of the string, tuple constructs a sequence from the list's elements, and set removes repeated equal elements. Sorting the set provides deterministic display in this example; it does not change the set's ordering contract.

Constructing a dictionary from an iterable requires appropriate key-value pairs, with hashable keys. Duplicate equal keys can replace earlier associated values.

Collection conversion generally does not recursively copy the objects within the collection. Converting a list into a tuple changes the outer representation, not the mutability of nested objects.

For n elements, materializing a list or tuple from a finite iterable typically requires O(n) element-processing work and O(n) reference storage, assuming ordinary constant-cost iteration. Set or dictionary construction is generally expected linear work under ordinary hash-table assumptions, but hashing and equality costs or collisions can increase the actual cost. Converting an infinite iterable without a stopping condition may never complete.

7. Text and binary data are different representations#

Text represents Unicode code points. Binary data represents bytes. Encoding and decoding are explicit transformations between these representations.

PYTHON
text = 'café' encoded = text.encode('utf-8') print(len(text), len(encoded)) print(encoded.decode('utf-8'))

Output:

4 5
café

The Unicode text has four code points but its UTF-8 representation uses five bytes. Use the encoding specified by the input or output protocol. Decoding invalid bytes with strict error handling can raise UnicodeDecodeError.

Calling str on a bytes object without an encoding does not automatically decode its contents as text; it produces a representation of the bytes object. Choose decode() or an explicit encoding-aware conversion when text is intended.

8. Conversion can lose information#

An explicit conversion is not always reversible. Turning a float into an int discards its fractional part. Turning a large integer into a float can round away significant digits. Converting a sequence into a set can remove duplicates and ordering information.

PYTHON
from decimal import Decimal value = 2**53 + 1 print(value, int(float(value))) print(Decimal('0.1') == Decimal(0.1))

Output on the tested binary64 platform:

9007199254740993 9007199254740992
False

The original integer is exact, but conversion to a binary64 float rounds it to a nearby representable value. Constructing Decimal from a float preserves the float's existing approximation, while constructing Decimal from text preserves the intended decimal value.

For exact identifiers, counts and decimal quantities, choose a representation that preserves the relevant information from the beginning. Converting a rounded value to a more precise type later cannot recover the lost original information.

9. Runtime conversion is not a type annotation or typing.cast#

Type annotations communicate expected types to readers and static analysis tools. The typing.cast function is a static typing aid and does not actually convert its argument at runtime.

PYTHON
from typing import cast value = cast(int, '7') print(type(value).__name__, type(int(value)).__name__)

Output:

str int

The cast call returns the original string unchanged. The int call performs the actual runtime conversion.

Avoid using typing.cast merely to hide a real type mismatch. Use runtime validation or conversion when input comes from an external boundary and its representation may not satisfy the required contract.

10. Conversion protocols for custom objects#

Custom types can implement appropriate special methods to participate in built-in conversion operations.

PYTHON
class Quantity: def __int__(self): return 7 print(int(Quantity()))

Output:

7

This class defines an integer conversion contract through __int__. Other operations can use protocols such as __float__, __complex__, __str__ and __bool__, depending on the operation.

The __index__ protocol represents lossless integer interpretation for operations that require an integer-like value, rather than truncating an arbitrary number.

PYTHON
import operator print(operator.index(3))

Output:

3

operator.index(3.0) raises TypeError even though 3.0 has a whole-number value. The ordinary float type does not implement the required integer-index protocol. This distinction matters when a function requires a valid index or count rather than just a numerical approximation.

Conversion methods implemented by custom classes may perform arbitrary work or raise exceptions. Do not assume every conversion has constant cost or is free of side effects.

11. What happens when conversion fails?#

Python raises an exception when the supplied value does not meet a conversion operation's requirements.

ExpressionExpected exception
int('3.5')ValueError
int(None)TypeError
int(float('inf'))OverflowError
int(float('nan'))ValueError
2 + '3'TypeError
operator.index(3.0)TypeError

ValueError commonly indicates an acceptable kind of input with an unacceptable value or format. TypeError commonly indicates an unsupported type or operation. OverflowError can indicate an unrepresentable numerical result. The actual exception depends on the conversion's documented contract and the input object.

The six cases above were tested independently. Catch expected exceptions near the relevant conversion boundary and handle them according to the application contract. Avoid a broad except clause that hides unrelated programming errors.

12. Practical example: validating a quantity from a form#

A form might provide a quantity as text. Conversion and validation are separate tasks: obtaining an integer does not prove that it is a valid order quantity.

PYTHON
def parse_quantity(text): if not isinstance(text, str): raise TypeError('expected text') value = int(text, 10) if value < 0: raise ValueError('negative quantity') return value print([parse_quantity(s) for s in ['0', '12', ' +3 ']])

Output:

[0, 12, 3]

This parser accepts the decimal integer syntax recognized by int with base 10, including the whitespace and sign in the example. It rejects negative numerical results. The following independent inputs were also tested:

InputResult
'3.5'ValueError
'-1'ValueError
NoneTypeError

The function intentionally permits zero. A real application should specify whether zero is acceptable, whether Unicode digits and underscores are allowed, whether there is a maximum quantity, and how input length is limited. Python's built-in integer string grammar is broader than some application-specific formats.

For untrusted input, enforce sensible size and business limits. CPython also has a configurable limit on certain large integer-string conversions. Parsing cost depends on input length, number base and implementation algorithms; do not assume converting an arbitrarily long decimal string is constant-time or even strictly linear.

13. Best practices and common mistakes#

  • Use explicit conversion when the required representation is known and input is not already in that representation.
  • Distinguish parsing, numerical conversion, formatting, serialization and runtime validation.
  • Preserve exact values by avoiding unnecessary intermediate floating-point conversions.
  • Check whether converting a collection discards duplicates, ordering or independence of nested objects.
  • Handle expected conversion exceptions and validate application-level ranges.
  • Do not use eval to convert untrusted input into Python objects.
  • Use documented text encodings at I/O boundaries.
  • Avoid confusing typing.cast with actual runtime conversion.

Frequently asked questions#

Does type conversion change the original variable's type?#

Conversion produces a result of the requested representation, according to the operation's contract. Assigning that result to a name rebinds it. The original object's type is not changed by ordinary conversion.

Is Python type conversion always automatic?#

No. Some compatible numeric operations perform implicit conversion, but incompatible types are not automatically converted in every context.

Why does int(3.9) return 3 instead of 4?#

The int constructor truncates a finite float toward zero. It does not round to the nearest integer.

Is every conversion reversible?#

No. Rounding, truncation, duplicate removal and representation changes can lose information.

Can bool('False') return False?#

No. An ordinary nonempty string is truthy. Explicit text parsing is needed to interpret that spelling as a Boolean flag.

What is the difference between conversion and validation?#

Conversion obtains a representation; validation checks whether the resulting value satisfies the required format, type, range or business rules. A successfully converted negative integer may still be an invalid quantity.

Interview-ready answer#

Type conversion in Python means obtaining a value of a different type using implicit numeric conversion or an explicit operation such as int(), float(), str(), bool() or list(). For example, adding an integer and a float produces a float in ordinary built-in arithmetic, while int("42") explicitly parses integer text. Python does not automatically convert incompatible operands in every operation. Conversions can fail with TypeError, ValueError or OverflowError, and some can lose precision or information. In production code, choose the appropriate conversion contract, validate external data and handle expected exceptions.

Official references#

Verification note: Eleven behavior-test groups and nine expected-exception cases passed locally on CPython 3.13.5, covering numeric, textual, Boolean, collection, encoding, custom conversion and validation semantics. The Mermaid flowchart was manually reviewed for standard fenced syntax and conceptual accuracy; the local Mermaid package and CLI were unavailable. Official references are supplied under the authorized offline research exception and were not checked live. Public-site rendering remains unverified.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design