Python Data Types Explained: Numbers, Strings, Collections and None
What are data types in Python?
A data type in Python is the kind of value an object holds, which decides the operations it supports. The built-in types include numbers (int, float, complex), text (str), bool, None, and the collections list, tuple, set and dict. Variables have no fixed type; the value they refer to does.
Key terms: object, type, mutable and immutable
- Object: every value in Python, from
5to a whole list, is an object with a type and an identity. - Type: returned by
type(value). Useisinstance(value, int)to check it in code. - Mutable: the object can be changed in place after creation (
list,dict,set). - Immutable: the object can never change; operations create a new object instead (
int,float,str,tuple,bool,None).
If you are new to Python, read Python basics first for variables and the REPL.
Numbers: int, float and complex
int holds whole numbers of any size. float holds decimal numbers in binary floating point, so some decimals cannot be stored exactly. complex numbers have a real and an imaginary part written with j.
big = 2 ** 100 # ints have no fixed size limit
print(7 / 2, 7 // 2, 7 % 2) # 3.5 3 1
print(0.1 + 0.2) # 0.30000000000000004
print(round(0.1 + 0.2, 2)) # 0.3
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2")) # 0.3
z = 3 + 4j
print(z.real, z.imag, abs(z)) # 3.0 4.0 5.0 Strings and their most useful methods
A str is an immutable sequence of Unicode characters. You can index and slice it like a list, but every method returns a new string rather than changing the original.
name = " Priya Sharma "
clean = name.strip() # "Priya Sharma"
print(clean.upper()) # PRIYA SHARMA
print(clean.lower().title()) # Priya Sharma
print(clean.split()) # ['Priya', 'Sharma']
print("-".join(["2026", "11", "10"])) # 2026-11-10
print(clean.replace("Sharma", "S.")) # Priya S.
print(clean.startswith("Pri")) # True
print(clean.find("Sh")) # 6
print(clean[0], clean[-1], clean[:5]) # P a Priya
print(f"{clean!r} has {len(clean)} characters")Strings can use single or double quotes, and triple quotes for text that spans several lines. Use in to test for a substring ("Sharma" in clean) and * to repeat ("-" * 20). Joining with "".join(parts) is the usual way to build a long string from many pieces.
Because strings are immutable, name.strip() on its own does nothing useful; you must assign the result. For complex pattern matching, see our regular expressions guide.
bool and None
bool has two values, True and False, produced by comparisons and combined with and, or and not. bool is a subclass of int, so True + True is 2. None is the single value of type NoneType and means "no value", for example the result of a function with no return.
result = None
if result is None: # use "is", not "==", for None
print("not calculated yet")
print(sum([True, False, True])) # 2: counts the True values Collections: list, tuple, set and dict
| Type | Literal | Ordered | Mutable | Duplicates | Typical use |
|---|---|---|---|---|---|
| list | [1, 2, 2] | Yes | Yes | Allowed | A sequence you add to and change |
| tuple | (1, 2, 2) | Yes | No | Allowed | A fixed record, such as coordinates |
| set | {1, 2} | No | Yes | Removed | Unique items and fast membership tests |
| dict | {"a": 1} | Keeps insertion order | Yes | Keys unique | Looking up values by key |
cities = ["Pune", "Delhi"]
cities.append("Pune")
point = (18.52, 73.86)
lat, lon = point # tuple unpacking
unique = set(cities) # {'Pune', 'Delhi'}
print("Delhi" in unique) # True
stock = {"pen": 40, "book": 12}
stock["bag"] = 5
print(stock.get("ink", 0)) # 0 instead of KeyError
for item, qty in stock.items():
print(item, qty)
empty_set = set() # {} is an empty dict, not a setLists also support comprehensions, a compact way to build a new collection from an existing one: [m * 2 for m in marks if m > 50] doubles every mark above 50. The same syntax with braces builds sets and dicts, for example {name: len(name) for name in cities}.
Dictionary keys and set members must be hashable, which in practice means immutable: a tuple can be a key, a list cannot. How these structures perform is covered in our data structures guide.
Mutability, type conversion and truthiness
Why mutability matters
Assignment never copies; it makes a second name for the same object. With a mutable object, a change through one name is visible through the other.
a = [1, 2, 3]
b = a # same list
b.append(4)
print(a) # [1, 2, 3, 4]
c = a.copy() # shallow copy: a new list
c.append(5)
print(a, c) # [1, 2, 3, 4] [1, 2, 3, 4, 5]Converting between types
print(int("42"), float("3.5"), str(99)) # 42 3.5 99
print(int(7.9)) # 7: truncates toward zero
print(list("abc")) # ['a', 'b', 'c']
print(tuple([1, 2])) # (1, 2)
print(dict([("x", 1)])) # {'x': 1}
print(bool("False")) # True: any non-empty string
# int("3.5") raises ValueError; use int(float("3.5"))Truthiness
In an if or while, every value counts as true or false. The falsy values are False, None, zero of any numeric type, and empty collections: "", [], (), {}, set() and range(0). Everything else is truthy, so if items: is the idiomatic way to check that a list is not empty.
Practical exercise: a shopping list analyser
Write a script that starts from raw = "milk, eggs, Milk , bread, eggs" and produces clean, typed data.
- Split the string on commas and use
strip()andlower()on each item to build a list. - Convert the list to a set and print how many unique items there are.
- Build a dict counting how often each item appears, using
counts[item] = counts.get(item, 0) + 1. - Print each item and count sorted alphabetically.
- Done looks like this: three unique items, with counts bread 1, eggs 2 and milk 2.
- Extension: store prices in a second dict as
Decimalvalues and print the total cost.
Next, package this logic into reusable Python functions. The PHP Foundation course covers the equivalent types in PHP.
Common mistakes
- Comparing floats with
==and being surprised that0.1 + 0.2 == 0.3isFalse. - Calling a string method such as
strip()without assigning the result, forgetting that strings are immutable. - Writing
{}to create an empty set, which actually creates an empty dict. - Assuming
b = acopies a list, then changingband unexpectedly changingatoo. - Using
bool("False")to parse user input; every non-empty string is truthy.
Frequently asked questions
Does Python have a char type or a separate double type?
No. A single character is just a str of length one, and float is already double precision in CPython. There is no separate double or long type in Python 3.
When should I use a tuple instead of a list?
Use a tuple for a fixed group of related values that should not change, such as a date or coordinates, or when you need it as a dictionary key. Use a list when items will be added, removed or reordered.
Do type hints change the type of a variable?
No. Hints such as age: int = 30 are notes for readers and tools like mypy. Python does not enforce them at run time, so assigning a string later still works.
Is a dict ordered in Python?
Yes. Since Python 3.7 the language specification states that dictionaries keep the order in which keys were inserted. Sets have no defined order.