Skip to content

Latest commit

 

History

History
325 lines (231 loc) · 5.52 KB

File metadata and controls

325 lines (231 loc) · 5.52 KB

Python Type Casting (Type Conversion)

Type casting (or type conversion) is the process of converting one data type into another using Python's built-in conversion functions.

Note: Not every conversion is valid. Invalid conversions raise TypeError or ValueError.


Type Conversion Overview

From Can Convert To
str int, float, complex, list, tuple, set, frozenset, bytes, bytearray, bool
int str, float, complex, bool, bytes
float str, int, complex, bool
complex str, bool
list str, tuple, set, frozenset, bool, bytes*, bytearray*
tuple str, list, set, frozenset, bool, bytes*, bytearray*
range list, tuple, set, frozenset, bool
dict list, tuple, set, frozenset, bool, str
set list, tuple, frozenset, bool, str
frozenset list, tuple, set, bool, str
bool int, float, complex, str
bytes str (decode), list, tuple, set, bytearray, bool
bytearray bytes, list, tuple, set, bool, str (decode)
memoryview bytes, bytearray, list, bool
NoneType bool, str

***** bytes() and bytearray() require iterable elements to be integers in the range 0–255.


1. String (str)

s = "123"

int(s)         # 123
float(s)       # 123.0
complex(s)     # (123+0j)
bool(s)        # True

list(s)        # ['1', '2', '3']
tuple(s)       # ('1', '2', '3')
set(s)         # {'1', '2', '3'}
frozenset(s)   # frozenset({'1', '2', '3'})

bytes(s, "utf-8")
bytearray(s, "utf-8")

2. Integer (int)

x = 10

str(x)         # '10'
float(x)       # 10.0
complex(x)     # (10+0j)
bool(x)        # True

bytes(x)       # 10 zero bytes

3. Float (float)

x = 10.75

int(x)         # 10
str(x)         # '10.75'
complex(x)     # (10.75+0j)
bool(x)        # True

4. Complex (complex)

x = 3 + 4j

str(x)
bool(x)

# Invalid
# int(x)
# float(x)

5. List (list)

L = [1, 2, 3]

tuple(L)
set(L)
frozenset(L)
str(L)
bool(L)
bytes(L)
bytearray(L)

6. Tuple (tuple)

T = (1, 2, 3)

list(T)
set(T)
frozenset(T)
str(T)
bool(T)
bytes(T)
bytearray(T)

7. Range (range)

r = range(5)

list(r)
tuple(r)
set(r)
frozenset(r)
bool(r)

8. Dictionary (dict)

d = {"a": 1, "b": 2}

list(d)        # ['a', 'b']
tuple(d)
set(d)
frozenset(d)
str(d)
bool(d)

Get Values

list(d.values())

Get Items

list(d.items())

9. Set (set)

s = {1, 2, 3}

list(s)
tuple(s)
frozenset(s)
str(s)
bool(s)

10. Frozen Set (frozenset)

fs = frozenset({1, 2, 3})

list(fs)
tuple(fs)
set(fs)
str(fs)
bool(fs)

11. Boolean (bool)

b = True

int(b)         # 1
float(b)       # 1.0
complex(b)     # (1+0j)
str(b)         # 'True'

12. Bytes (bytes)

b = b"Hello"

str(b)          # "b'Hello'"
b.decode()      # 'Hello'

list(b)
tuple(b)
set(b)
bytearray(b)
bool(b)

13. Bytearray (bytearray)

ba = bytearray(b"Hello")

bytes(ba)
list(ba)
tuple(ba)
set(ba)
ba.decode()
bool(ba)

14. Memoryview (memoryview)

mv = memoryview(b"Hello")

bytes(mv)
bytearray(mv)
list(mv)
bool(mv)

15. NoneType

x = None

bool(x)        # False
str(x)         # 'None'

# Invalid
# int(None)
# float(None)
# list(None)

Truth Values (bool())

The following values evaluate to False:

bool(0)
bool(0.0)
bool(0j)

bool("")
bool([])
bool(())
bool({})
bool(set())
bool(frozenset())
bool(range(0))

bool(b"")
bool(bytearray())

bool(None)

Everything else evaluates to True.


Common Invalid Type Casts

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

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

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

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

bytes([300])        # ValueError

Summary

  • Use Python's built-in conversion functions such as int(), float(), str(), list(), and tuple() for type casting.
  • Some conversions are lossy (e.g., floatint truncates the decimal part).
  • Not every conversion is valid; invalid conversions raise TypeError or ValueError.
  • Empty containers and zero-like values evaluate to False; everything else evaluates to True.