Python Type Conversions Cheat Sheet
Learn implicit and explicit type conversions in Python. Convert between strings, integers, floats, lists, sets, and dictionaries.
Basic Primitive Casting
Methods to explicitly convert variables between primitive data types.
| Method | Syntax | Description |
|---|---|---|
| int() | int(x, base=10) | Converts x to an integer. Can parse strings with an optional numeric base. |
| float() | float(x) | Converts a number or numeric string to a floating-point number. |
| str() | str(object) | Returns the string representation of an object. |
| bool() | bool(x) | Converts x to boolean, evaluating to True or False according to truth value testing. |
Data Structure & Collection Conversion
Transforming container collections into different representations.
| Method | Syntax | Description |
|---|---|---|
| list() | list(iterable) | Converts any iterable sequence (e.g. tuple, set, dict keys) into a mutable list. |
| tuple() | tuple(iterable) | Converts any iterable sequence into an immutable tuple. |
| set() | set(iterable) | Converts an iterable into a set, deduplicating any repeat elements. |
| dict() | dict(iterable) | Constructs a dictionary from key-value pairs, typically a list of tuples. |
| zip() | zip(*iterables) | Pairs elements from multiple iterables, ready to be cast into a list or dictionary. |
Frequently Asked Questions
What values evaluate to False in a boolean context?
Empty collections ([], (), {}, set()), None, False, numeric zeros (0, 0.0), and empty strings ("") evaluate to False. All other values evaluate to True.
Can I convert a list of tuples into a dictionary?
Yes, if the tuples contain exactly two elements (key, value), you can call dict(list_of_tuples) to generate a dictionary.
Keep Learning
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Type Hints
Learn how to write type hints in Python. Improve code quality, enable autocompletion, and leverage mypy for static code analysis.
How to Check Data Type in Python
Learn how to check data types in Python. Understand when to use type() vs isinstance(), handle custom classes, and write safe type check validations.
Python vs TypeScript: Dynamic Scripting vs Type-Safe Web
Compare Python and TypeScript. Learn about structural type systems, decorator metadata, compiler checks, web runtimes, and developer tooling.