Type Conversions

You will learn how to convert values from one data type to another in Python in this lesson.

Data type conversion functions

To convert a value from one data type to another, it is often possible to use the name of the desired data type as if it were a function. For example:

Conversion Result
int(5.7) 5
int("5") 5
float(5) 5.0
float("5.7") 5.7
bool("False") True
str([1,2,3]) ‘[1,2,3]’

Note: When working with Boolean data types, the following things are considered false: False, None, 0, 0.0, and the empty string.

Other data types that can be used as conversion functions are list, set, tuple, and dict (dictionary). A few important points to remember are:

  • When you convert from a dict to any of the other types, you get only the keys, not the values.
  • You can convert a list, set, or tuple to a dict only if the elements are grouped in twos, like, a list of 2- tuples (tuples with two elements).
  • Sets have no intrinsic ordering, so converting to or from a set does not necessarily preserve the order of the elements.

Difference between type and isinstance functions

The function type(x) will return a value that can be compared to the name of a type (not to a string representation of that name). For example, the test type(5) == int will return True, but type(5) == "int" will return False.

Get hands-on with 1400+ tech skills courses.