Data Types

Every value in Python has a type, and those types fall into a few natural families.

Introduction

Python's built-in types split into three broad groups: numbers (int, float, bool, complex), sequences — ordered collections that support indexing and slicing (str, list, tuple) — and mappings — collections accessed by key instead of position (dict).

  • int — whole numbers, positive or negative, with no fixed size limit
  • float — numbers with a decimal point, or written in exponential form (3.5e-2)
  • boolTrue or False; internally treated as 1 and 0
  • str — text, a sequence of characters
  • list — an ordered, mutable collection, written with [ ]
  • tuple — an ordered, immutable collection, written with ( )
  • dict — key-value pairs, written with { }
print(type(42))
print(type(3.14))
print(type(True))
print(type("hello"))
print(type([1, 2, 3]))
<class 'int'> <class 'float'> <class 'bool'> <class 'str'> <class 'list'>

Mutable

Mutable types can be changed in place — modifying them updates the existing object instead of creating a new one. Lists, dictionaries, and sets are all mutable.

scores = [10, 20, 30]
scores[0] = 99
print(scores)

profile = {"name": "Bytewise"}
profile["name"] = "ProgramWise"
print(profile)
[99, 20, 30] {'name': 'ProgramWise'}

Immutable

Immutable types can never be changed in place — any "change" actually builds a brand new object. int, float, bool, str, and tuple all work this way.

name = "Byte"
name[0] = "b"
TypeError: 'str' object does not support item assignment

The same happens with tuples — you can build a new tuple, but you can't modify one that already exists:

point = (1, 2, 4)
point[0] = 9
TypeError: 'tuple' object does not support item assignment

Type Casting

Type casting converts a value from one type to another. Python does this two ways: implicitly, on its own during a calculation, or explicitly, when you call a conversion function yourself.

print(3 + 6.9)
print(True + 1)
9.9 2

In the first line, 3 is silently converted to a float before the addition happens. In the second, True is treated as the integer 1.

print(int("10"))
print(float("1.23"))
print(str(99))
10 1.23 99

Explicit conversions can fail, though — a string only converts to int if it looks like a whole number:

print(int("10.5"))
ValueError: invalid literal for int() with base 10: '10.5'