Python - Type Casting

python logo pixel art

Python allows you to convert one data type to another.


Type Conversion - Implicit vs Explicit

# Implicit Conversion
x = 10
y = 5.5
print(type(x + y)) # float
# Explicit Conversion
x = 10
y = 5
z = float(x + y)
print(type(z)) # float

Common Type Conversions

Float to Int

int(3.14) # 3

Tuple to List

list((1, 2, 3)) # [1, 2, 3]

List to Tuple

tuple([1, 2, 3]) # (1, 2, 3)

Set to List

list({1, 2, 3}) # [1, 2, 3]

List to Set

set([1, 2, 3]) # {1, 2, 3}