🐍 Python📅 Day 4

Data Types in Python

Numbers, strings, booleans, lists, tuples, dicts, sets — Python's built-in types and how to convert between them.

🎯

Learning objectives

  • Identify Python's core built-in types
  • Use type() and isinstance() for runtime checks
  • Convert between types safely

💡 Key points

  • Numeric: int (arbitrary precision), float (64-bit), complex.
  • Text: str — immutable Unicode.
  • Boolean: bool — subclass of int (True == 1, False == 0).
  • Collections: list (mutable), tuple (immutable), set (unique), dict (key→value).
  • None is its own type (NoneType) — used to represent 'no value'.

💻 Code examples(4)

#1Numeric types
python
a = 42            # int
b = 3.14          # float
c = 2 + 3j        # complex
big = 10 ** 100   # no overflow — arbitrary precision int

print(type(a), type(b), type(c))
Integers grow as large as memory allows. Floats are standard 64-bit IEEE 754.
#2Strings
python
s1 = "double quotes"
s2 = 'single quotes'
s3 = """multi
line"""
s4 = f"Hello {s1}"     # f-string

print(len(s1))         # 13
print(s1.upper())      # DOUBLE QUOTES
Strings are immutable — every 'modification' returns a new string. f-strings are the modern way to interpolate.
#3Collections at a glance
python
lst = [1, 2, 3]              # list, mutable
tup = (1, 2, 3)              # tuple, immutable
st  = {1, 2, 3}              # set, unique + unordered
dct = {"a": 1, "b": 2}       # dict, key→value

lst.append(4)                # OK
# tup[0] = 99                # ❌ TypeError
st.add(3)                    # no effect (already present)
dct["c"] = 3
#4Type conversion
python
int("42")           # 42
float("3.14")       # 3.14
str(100)            # "100"
list("abc")         # ['a', 'b', 'c']
bool(0), bool("")   # (False, False)
bool(1), bool("x")  # (True, True)
int('3.14') raises ValueError — for a float string, do int(float('3.14')).

🎯 Practice

Q1. What does type(True) return?+

<class 'bool'>. bool is a subclass of int, so True + 1 == 2.

Q2. What is the difference between a list and a tuple?+

List is mutable (can add/remove/change items). Tuple is immutable — fixed after creation. Tuples are lighter and hashable (usable as dict keys).

Q3. Convert the string '123' to an int, add 10, print result.+

print(int('123') + 10) # 133

📝 Notes

Falsy values

The following are falsy in a boolean context:

  • False, None
  • 0, 0.0
  • "", [], (), {}, set()

Everything else is truthy. Idiom:

if items:
    process(items)   # runs only when list is non-empty

Type checking

isinstance(x, int)         # True/False
isinstance(x, (int, float)) # accepts either

Prefer isinstance() over type(x) == int — it handles subclasses correctly.