Skip to content

Latest commit

 

History

History
340 lines (231 loc) · 7.24 KB

File metadata and controls

340 lines (231 loc) · 7.24 KB

Python Type Casting (Type Conversion)

Type casting (type conversion) means converting one data type into another using Python's built-in functions.

Note

  • Invalid conversions raise either TypeError or ValueError.
  • Some conversions only work when the value is valid.

Conversion Table

From Valid Conversions Invalid / Not Possible
str int*, float*, complex*, bool, list, tuple, set, frozenset, bytes, bytearray memoryview, most dict() conversions
int str, float, complex, bool, bytes list, tuple, set, frozenset, dict, bytearray, memoryview
float int, str, complex, bool bytes, bytearray, list, tuple, set, frozenset, dict, memoryview
complex str, bool int, float, bytes, bytearray, list, tuple, set, frozenset, dict, memoryview
list tuple, set, frozenset, str, bool, bytes**, bytearray** int, float, complex, memoryview
tuple list, set, frozenset, str, bool, bytes**, bytearray** int, float, complex, memoryview
range list, tuple, set, frozenset, bool int, float, complex, bytes, bytearray, dict, memoryview
dict list, tuple, set, frozenset, str, bool int, float, complex, bytes, bytearray, memoryview
set list, tuple, frozenset, str, bool int, float, complex, bytes, bytearray, dict, memoryview
frozenset list, tuple, set, str, bool int, float, complex, bytes, bytearray, dict, memoryview
bool int, float, complex, str list, tuple, set, frozenset, dict, bytes, bytearray, memoryview
bytes decode(), list, tuple, set, bytearray, bool int, float, complex, dict, memoryview
bytearray bytes, list, tuple, set, decode(), bool int, float, complex, dict, memoryview
memoryview bytes, bytearray, list, bool int, float, complex, tuple, set, frozenset, dict, str
None bool, str int, float, complex, list, tuple, set, frozenset, dict, bytes, bytearray, memoryview

* Numeric string required.

** Elements must be integers between 0–255.


Complete Invalid Conversion Examples

String (str)

int("abc")              # ValueError
float("hello")          # ValueError
complex("abc")          # ValueError

memoryview("Hello")     # TypeError

dict("hello")           # ValueError

Integer (int)

list(10)                # TypeError
tuple(10)               # TypeError
set(10)                 # TypeError
frozenset(10)           # TypeError

dict(10)                # TypeError

bytearray(10)           # Creates 10 zero bytes (VALID)

memoryview(10)          # TypeError

Float (float)

bytes(10.5)             # TypeError
bytearray(10.5)         # TypeError

list(10.5)              # TypeError
tuple(10.5)             # TypeError
set(10.5)               # TypeError
frozenset(10.5)         # TypeError

dict(10.5)              # TypeError

memoryview(10.5)        # TypeError

Complex (complex)

int(3+4j)               # TypeError
float(3+4j)             # TypeError

bytes(3+4j)             # TypeError
bytearray(3+4j)         # TypeError

list(3+4j)              # TypeError
tuple(3+4j)             # TypeError
set(3+4j)               # TypeError
frozenset(3+4j)         # TypeError

dict(3+4j)              # TypeError

memoryview(3+4j)        # TypeError

List (list)

int([1,2,3])            # TypeError
float([1,2,3])          # TypeError
complex([1,2,3])        # TypeError

memoryview([1,2,3])     # TypeError

Tuple (tuple)

int((1,2,3))            # TypeError
float((1,2,3))          # TypeError
complex((1,2,3))        # TypeError

memoryview((1,2,3))     # TypeError

Range (range)

int(range(5))           # TypeError
float(range(5))         # TypeError

bytes(range(300))       # ValueError

dict(range(5))          # TypeError

memoryview(range(5))    # TypeError

Dictionary (dict)

int({"a":1})            # TypeError
float({"a":1})          # TypeError
complex({"a":1})        # TypeError

bytes({"a":1})          # TypeError
bytearray({"a":1})      # TypeError

memoryview({"a":1})     # TypeError

Set (set)

int({1,2,3})            # TypeError
float({1,2,3})          # TypeError
complex({1,2,3})        # TypeError

bytes({300})            # ValueError

memoryview({1,2,3})     # TypeError

Frozenset (frozenset)

int(frozenset({1}))     # TypeError
float(frozenset({1}))   # TypeError
complex(frozenset({1})) # TypeError

memoryview(frozenset()) # TypeError

Boolean (bool)

list(True)              # TypeError
tuple(True)             # TypeError
set(True)               # TypeError
frozenset(True)         # TypeError

dict(True)              # TypeError

bytes(True)             # b'\x00'

memoryview(True)        # TypeError

Bytes (bytes)

int(b"123")             # VALID -> 123
int(b"abc")             # ValueError

float(b"abc")           # ValueError

complex(b"abc")         # ValueError

dict(b"abc")            # TypeError

memoryview(b"abc")      # VALID

Bytearray (bytearray)

int(bytearray(b"123"))      # VALID -> 123
int(bytearray(b"abc"))      # ValueError

float(bytearray(b"abc"))    # ValueError

dict(bytearray(b"abc"))     # TypeError

memoryview(bytearray(b"abc"))   # VALID

Memoryview (memoryview)

int(memoryview(b"123"))     # TypeError
float(memoryview(b"123"))   # TypeError
complex(memoryview(b"123")) # TypeError

tuple(memoryview(b"123"))   # VALID

set(memoryview(b"123"))     # VALID

dict(memoryview(b"123"))    # TypeError

None

int(None)               # TypeError
float(None)             # TypeError
complex(None)           # TypeError

list(None)              # TypeError
tuple(None)             # TypeError
set(None)               # TypeError
frozenset(None)         # TypeError

dict(None)              # TypeError

bytes(None)             # TypeError
bytearray(None)         # TypeError

memoryview(None)        # TypeError

TypeError vs ValueError

TypeError

Raised when the data type is not supported.

list(10)
tuple(20)
int(3+4j)
float({})
memoryview("abc")

ValueError

Raised when the type is correct but the value is invalid.

int("abc")
float("hello")
complex("xyz")

bytes([300])
bytearray([300])

Truthy / Falsy

Falsy values

0
0.0
0j
""
[]
()
{}
set()
frozenset()
range(0)
b""
bytearray()
None

Everything else is Truthy.


Quick Revision

  • TypeError → Wrong data type.
  • ValueError → Wrong value.
  • int() cannot convert complex.
  • float() cannot convert complex.
  • list(), tuple(), set() require an iterable.
  • bytes() and bytearray() require integers from 0 to 255.
  • memoryview() only accepts bytes-like objects.
  • Empty containers are False.
  • Non-empty containers are True.