Converting types (int(), float(), str(), list()…)
Converting a type means calling the type's name, like int() or list(), to build a new value of that type from another one.
Used in 113 lessons of the course, from 00.03.
In Python, int, float, str, list, dict and tuple are types, and you call them like functions. int("42") takes the string "42" and returns the integer 42. The original value doesn't change: you get a new one.
Each conversion has its own rules. int(3.9) cuts off the decimals and gives 3; it doesn't round. int("abc") fails with ValueError, because there is no number in it. list("hola") splits an iterable into its elements.
It's written this way because the type knows how to build itself from other values. You'll see it a lot in the course, for example in dict(Counter(...)): Counter counts the cells and dict(...) turns the result into a plain dict that prints cleanly.
list("abc") # ['a', 'b', 'c']
Reach for it when: you have a value of one type and need another: a string that holds a number, a number to show as text, or an iterable you want as a list or dict.
Examples
Common mistake
n = int("3.5")
print(n)Why: int() only accepts strings that are whole numbers. "3.5" has a decimal point, so it fails.
How to write it: Convert to float first, then to int: int(float("3.5")).
Common mistake
print("Total: " + 5)Why: Python doesn't turn the number into text for you with +. A string and an int can't be added.
How to write it: Convert with str(5) or use an f-string: f"Total: {5}".
