Convert Data Types in Python

Learn how to convert between Python data types using built-in constructor functions like int(), float(), str(), list(), and dict(). Master safe type conversion patterns.

5 min read

Converting values from one data type to another is a skill you will use in almost every Python program you write. User input arrives as strings and needs to become numbers before calculations. Numbers need to become strings before they can be written to files or displayed in user interfaces. Lists need to become tuples to serve as dictionary keys, and tuples need to become sets when you want to eliminate duplicates. Python makes type conversion straightforward with a family of built-in constructor functions, each named after the target type. The int function converts compatible values to integers. The float function converts to floating-point numbers. The str function converts to strings. The bool, list, tuple, set, and dict functions each convert to their respective types following well-defined rules.

If you have explored the Python data types overview and learned how to check data types with the type function, type conversion is the natural next step. Knowing what type a value has is only half the picture. Knowing how to deliberately change that type into another one gives you full control over how data flows through your program. This article covers every major conversion function, explains the rules that each one follows, and highlights the common pitfalls that trip up beginners.

Numeric conversions: int(), float(), and complex()

The int function converts values to integers. When given a string, int parses it as a decimal integer by default, accepting an optional leading plus or minus sign. The string must contain only digit characters and the optional sign. Leading and trailing whitespace is stripped automatically, but any other non-digit character causes a ValueError. When given a float, int truncates toward zero, discarding the fractional part without rounding. The value 3.9 becomes 3, and -3.9 becomes -3. If you need rounding instead of truncation, call the round function before converting to int. The int function also accepts an optional second argument specifying a numeric base, which lets you parse binary strings like "1010" as base 2, octal strings as base 8, and hexadecimal strings as base 16.

The float function converts values to floating-point numbers. When given a string, float parses it as a decimal number with an optional decimal point and an optional exponent specified with the letter e. Strings like 3.14, -0.5, and 1e-10 are all valid float inputs. When given an integer, float returns the equivalent floating-point representation. The float function also accepts the special strings inf, -inf, and nan for infinity, negative infinity, and not-a-number values respectively. Converting very large integers to floats may lose precision because floats can only represent about 15 to 17 significant decimal digits exactly.

The complex function converts values to complex numbers. When given two numeric arguments, it treats the first as the real part and the second as the imaginary part. When given a single numeric argument, it returns a complex number with that real part and an imaginary part of zero. When given a string like 3+4j, it parses the string as a complex literal. Converting a complex number to an integer or float is not directly possible. You must first decide whether you want the real part, the imaginary part, or the magnitude, and extract that value using the appropriate attribute or function.

String conversion: str()

The str function is the most versatile conversion function in Python because every object has a string representation. Calling str on any value returns a human-readable string version of that value. Numbers become their decimal string equivalents. Lists become strings showing their contents enclosed in square brackets with commas between items. Dictionaries become strings with curly braces, key-value pairs, and commas. Custom objects use the string returned by their class's special method for string conversion, or a default representation that includes the class name and memory address if no custom method is defined.

pythonpython
num_str = str(42)
float_str = str(3.14159)
list_str = str([1, 2, 3])
bool_str = str(True)

After running this code, num_str holds the string "42", float_str holds "3.14159", list_str holds "[1, 2, 3]", and bool_str holds "True". The str function never raises an error on valid Python objects, which makes it safe to use anywhere you need a guaranteed string output. For more control over numeric formatting, f-strings and the format method provide options like specifying the number of decimal places, padding with zeros, and aligning text within a fixed width.

Boolean conversion: bool()

The bool function converts any value to its boolean truth value. The conversion follows Python's truthiness rules, which are consistent and predictable. Values that are considered falsy and convert to False include the integer zero, the float zero, the complex zero, the boolean False itself, None, empty strings, empty lists, empty tuples, empty dictionaries, empty sets, empty ranges, and empty frozen sets. Every other value is considered truthy and converts to True. This includes non-zero numbers, non-empty strings and collections, and all custom objects that do not define a custom truth-value method.

The bool conversion is most useful when you need an explicit True or False value rather than relying on implicit truthiness in an if-statement condition. Storing the result of bool in a variable makes your intent clear to readers and prevents subtle bugs where a falsy value like zero or an empty string is treated the same as None. The bool function is also useful in filter operations and in any situation where you need to compactly represent whether a value exists.

Collection conversions: list(), tuple(), set(), and dict()

The list, tuple, and set functions each accept an iterable argument and create a new collection of the corresponding type containing the iterable's items. When you convert a string to a list, each character becomes a separate list element. Converting a string to a set gives you the set of unique characters in the string, with order not preserved. Converting a tuple to a list creates a mutable copy with the same items in the same order. Converting a list to a tuple creates an immutable copy. Converting a list to a set removes duplicates and loses ordering. Converting a list of key-value pairs to a dictionary creates a mapping from those pairs, where the first element of each pair becomes the key and the second becomes the value.

pythonpython
text = "hello"
chars_list = list(text)
chars_tuple = tuple(text)
unique_set = set(text)
pairs = [("a", 1), ("b", 2), ("c", 3)]
dictionary = dict(pairs)

The variables after these conversions hold: a list of five characters, a tuple of five characters, a set of four unique characters because the letter l appears twice and the set removes the duplicate, and a dictionary mapping "a" to 1, "b" to 2, and "c" to 3. The dict function also accepts keyword arguments for keys that are valid Python identifiers and accepts another dictionary to create a shallow copy. When converting between collection types, remember that sets require all elements to be hashable and dictionaries require all keys to be hashable. A list of lists cannot become a set or a dictionary key, but a list of tuples can.

Conversion that fails and how to handle it

Not every conversion makes sense, and Python raises errors when you attempt an impossible conversion. Passing a non-numeric string to int or float raises a ValueError. Trying to convert a complex number to an integer or float fails because there is no single obvious way to flatten two components into one. Passing an iterable with unhashable elements to the set or dict function raises a TypeError. The safest approach is to validate your input before attempting a conversion, or to wrap the conversion in a try-except block that catches the specific error and provides a fallback value or a helpful error message.

The article on implicit and explicit type conversion covers the difference between conversions you call deliberately and conversions that Python performs automatically behind the scenes. Both are important. Explicit conversion is what you do when you call int, float, or str in your own code. Implicit conversion is what Python does when you add an integer to a float and the integer is automatically promoted to a float so the addition can proceed.

Rune AI

Rune AI

Key Insights

  • Use built-in constructor functions like int(), float(), str(), and bool() to convert between types.
  • int() truncates floats toward zero; use round() first if you need mathematical rounding.
  • str() converts any value to its string representation and never raises an error.
  • bool() converts any value based on truthiness: zeros and empty containers become False, everything else True.
  • Converting to list, tuple, or set from strings splits into individual characters.
RunePowered by Rune AI

Frequently Asked Questions

How do I convert a string to an integer in Python?

Use the int() function: int('42') returns the integer 42. The string must contain only digits and optionally a leading plus or minus sign. int('3.14') raises a ValueError because the decimal point makes it a float string. Convert float strings by chaining: int(float('3.14')) returns 3 by truncating the fractional part. You can also specify a base: int('FF', 16) returns 255.

How do I convert a number to a string in Python?

Use the str() function: str(42) returns the string '42'. This works for all numeric types including int, float, and complex. You can also use f-strings like f'{42}' or the format() method like '{}'.format(42). For more control over formatting, use f-strings with format specifiers like f'{3.14159:.2f}' for two decimal places.

What happens when I convert a float to an integer?

The int() function truncates toward zero, discarding the fractional part without rounding. int(3.9) returns 3, and int(-3.9) returns -3. If you need rounding instead of truncation, use round() first: int(round(3.9)) returns 4. For floor or ceiling rounding, use math.floor() or math.ceil() before converting to int.

Conclusion

Python's built-in constructor functions provide a consistent and predictable way to convert values between types. The key functions are int(), float(), str(), bool(), list(), tuple(), set(), and dict(). Each follows clear rules about what inputs it accepts and what the output looks like. Mastering these conversions is essential for reading data from files, processing user input, and preparing values for storage or display.