Understanding Python variables and data types is the first real step to writing working programs. In this beginner guide to Python variables and data types with examples, you’ll learn what a variable is, the core built‑in data types in modern Python (3.11+ and valid through Python 3.14), how to choose the right type, how to check and convert types, and the difference between mutable and immutable objects. By the end, you’ll be able to write clean, simple code with confidence.
- Variables are names that point to values (objects). Values have types; names do not.
- Python is dynamically typed—rebind names freely; add optional type hints for clarity.
- Pick the type that matches your data: numbers, text, sequences, mappings, sets, bytes, or
None. - Know mutability:
list/dict/setare mutable;int/str/tupleare immutable. - Inspect with
type()/isinstance(); convert withint(),float(),str(),list(),dict(),set(). - Strings are Unicode; convert to bytes with
.encode()and back with.decode(). - Avoid common mistakes: mixing text and numbers without conversion, shadowing built‑ins, using
isinstead of==.
What is a variable in Python?
A variable is a name that points to a value (an object) in memory. Python is dynamically typed: you don’t declare types before using a variable. Assignment creates or updates the binding between a name and an object.
y = "Hello" # y points to a str
x = "Now text" # rebinding x to a new object (a str)
print(type(x), type(y))
<class 'str'> <class 'str'>How to create variables in Python
- Simple assignment uses the equals sign (=).
- Multiple assignment assigns several names at once.
- Unpacking pulls values out of sequences.
first, last = "Ada", "Lovelace"
x, y, z = 1, 2, 3
p, q = q, p # swap values
# Unpacking with a "star" to capture the rest
head, *middle, tail = [10, 20, 30, 40, 50]
print(head, middle, tail)
10 [20, 30, 40] 50Python variable rules and naming examples
- Names may include letters, digits, and underscores, but can’t start with a digit:
total_score,_hidden,name2are fine;2nameis not. - Python is case-sensitive:
Scoreandscoreare different. - Use snake_case for readability:
average_speed. - Don’t use keywords like
classorforas names. - Avoid shadowing built-ins like
listordict.
total_marks = 460
max_marks = 500
percentage = (total_marks / max_marks) * 100
print(student_name, round(percentage, 2))
Riya 92.0Do variables have types?
Values (objects) have types; variables are just names bound to those values. You can add optional type hints for readability and tooling; they don’t change runtime behavior.
age: int = 18
greeting: str = "Welcome"
valid: bool = TrueTip: In modern Python, prefer built-in generics for hints, for example list[int] or dict[str, float]. Type hints are checked by external tools (like editors or linters), not by Python itself.
Python data types explained
Here are the core built-in types you’ll use daily.
| Category | Type | Examples | Mutable? | Notes |
|---|---|---|---|---|
| Numbers | int, float, complex, bool | 42, 3.14, 2+3j, True | No | Use int(), float() to convert |
| Text | str | “hello”, “café” | No | Unicode text |
| Binary | bytes, bytearray, memoryview | b”data” | bytes: No, bytearray: Yes | For files, networks; needs encoding/decoding |
| Sequence | list, tuple, range | [1,2], (1,2), range(5) | list: Yes, tuple/range: No | Lists for changeable sequences |
| Mapping | dict | {“a”: 1, “b”: 2} | Yes | Preserves insertion order |
| Set | set, frozenset | {1,2,3} | set: Yes, frozenset: No | No duplicates; fast membership |
| Special | NoneType | None | n/a | Represents “no value” |
Numbers: int, float, bool (with examples)
b = 2.5 # float
c = a + b
is_pass = True # bool (True/False)
print(a, b, c, is_pass)
7 2.5 9.5 Trueprint(int("42")) # 42
print(float("3.14")) # 3.14
print(str(99)) # "99"
For money where precision matters, look at decimal.Decimal later; basic floats can have rounding issues.
Strings: Unicode text
print(s.upper(), len(s)) # CAFE 4
# f-strings for formatting
name = "Aman"
score = 91.5
print(f"{name} scored {score}%")
# Encoding to bytes and back
b = s.encode("utf-8")
print(b) # b'cafxc3xa9'
print(b.decode("utf-8")) # café
Lists and tuples
nums.append(4)
print(nums)
point = (10, 20) # tuple (immutable)
print(point[0], point[1])
[1, 2, 3, 4]
10 20Dictionaries (dict)
Dictionaries map keys to values. In modern Python, dicts preserve insertion order.
student["grade"] = "A"
print(student)
# Merge dicts
extra = {"roll": 23}
merged = student | extra
print(merged)
{'name': 'Riya', 'age': 19, 'grade': 'A'}
{'name': 'Riya', 'age': 19, 'grade': 'A', 'roll': 23}Sets
print(unique_marks) # duplicates removed
passed = {80, 85, 90}
honors = {90, 95}
print(passed & honors) # intersection
{80, 85, 90}
{90}None
if result is None:
print("No result yet")
No result yetMutable vs immutable types (for beginners)
Immutable objects can’t be changed after creation (like int, float, str, tuple). Mutable objects can change in place (like list, dict, set).
| Type | Mutable? | Beginner tip |
|---|---|---|
| int, float, bool, str, tuple, frozenset | No | Operations make new objects |
| list, dict, set, bytearray | Yes | Methods modify the same object |
a = 5
b = a
a += 1
print(a, b) # b is unchanged
# Mutable example
x = [1, 2]
y = x
x.append(3)
print(x, y) # y sees the change too
6 5
[1, 2, 3] [1, 2, 3]To avoid side effects with mutable types, copy them:
copy_list = orig.copy() # or list(orig)
orig.append(4)
print(orig, copy_list)
[1, 2, 3, 4] [1, 2, 3]How to choose the right data type for your variable
- Counts, IDs, and indexes:
int - Measurements with decimals (approximate):
float - Human‑readable text:
str - Ordered, changeable collection:
list - Fixed-size record:
tuple(e.g., coordinates) - Key–value records (like JSON objects):
dict - Unique items and fast membership checks:
set - Raw bytes for files/sockets:
bytesorbytearray - “No value yet”:
None
How to check data type in Python (with example)
Use type() to see the exact type and isinstance() to check against a broader category.
value = [1, 2, 3]
print(type(value)) # <class 'list'>
print(isinstance(value, list)) # True
print(isinstance(value, (list, tuple))) # True if list or tupleFrom input to correctly typed variable (flow)
strConverting between data types (casting)
age = int("18")
pi = float("3.1415")
# Numbers to strings
code = str(404)
# Sequence conversions
s = "abc"
print(list(s)) # ['a', 'b', 'c']
print(tuple(s)) # ('a', 'b', 'c')
print(set("aab")) # {'a', 'b'}
# dict from pairs
pairs = [("a", 1), ("b", 2)]
print(dict(pairs))
['a', 'b', 'c']
('a', 'b', 'c')
{'a', 'b'}
{'a': 1, 'b': 2}Modern assignment tips for beginners
- Augmented assignment modifies in place when possible:
+=,-=,|=(for sets/dicts in newer Python). - “Walrus operator” (
:=) assigns inside expressions. Handy for loops.
# Augmented assignment
total = 0
for n in [2, 4, 6]:
total += n
print(total)
# Walrus operator example
lines = ["first", "second", ""]
i = 0
while (line := lines[i]) != "":
print(line)
i += 112
first
secondCommon mistakes and how to avoid them
- Mixing text and numbers without conversion:
age = 18
print("Age: " + str(age)) # convert to str
print(f"Age: {age}") # or use f-strings - Shadowing built-ins:
# Avoid this
list = [1, 2, 3] # shadows built-in list()
del list # undo shadowing if it happens - Using
isinstead of==for value comparison:print([1,2] == [1,2]) # True (values equal)
print([1,2] is [1,2]) # False (different objects) - Forgetting that strings are Unicode and different from bytes:
data = "café"
# print(b"café") # invalid: bytes literal must be ASCII
b = data.encode("utf-8")
print(b.decode("utf-8"))
Beginner’s practical checklist: variables and data types
- ✓ Use snake_case names; never use keywords or shadow built-ins (e.g., don’t name a variable
list). - ✓ Decide the target type before storing data; note whether you need a mutable or immutable container.
- ✓ When reading input, validate and convert with
int()/float()/set()/dict(); handle errors withtry/except. - ✓ Prefer f-strings for output; avoid concatenating different types without
str(). - ✓ Use
==for value equality,isfor identity andis Nonechecks. - ✓ Copy mutable containers (
.copy()orlist(x)/dict(x)) when sharing would cause side effects. - ✓ Use
setfor uniqueness and fast membership,dictfor labeled records,tuplefor fixed-size groups. - ✓ For money, consider
decimal.Decimal; for JSON data, usedict/listwith thejsonmodule.
Quick practice
- Create variables for your name (str), age (int), and GPA (float). Print them in one sentence using an f-string.
- Given
scores = [88, 92, 75, 92], convert to a set to remove duplicates, then back to a sorted list. - Make a dict
personwith keysname,skills(list), andactive(bool). Append a new skill.
FAQ: Python variables and data types with examples
What is a variable in Python and how do I create one?
A variable is a name that refers to a value. Create one with assignment: count = 10, name = "Zara". Python binds the name to the object on the right-hand side.
What are the basic data types in Python with examples?
Common ones are int and float for numbers, bool for True/False, str for text, list/tuple/range for sequences, dict for key–value pairs, set/frozenset for unique collections, bytes for raw data, and None for “no value.” Example: age = 20, name = "Asha", tags = {"python", "beginner"}.
How do I choose the right data type for my Python variable?
Pick the type that best matches your task: numbers for math, strings for text, lists for ordered changeable items, tuples for fixed groups, dicts for labeled data, sets for uniqueness and fast membership, and bytes for file/network I/O.
What is the difference between mutable and immutable types in Python?
Immutable types (like int, str, tuple) can’t be changed after creation—operations create new objects. Mutable types (like list, dict, set) can be changed in place using methods (e.g., append(), assignment to keys).
How can I check or convert a variable’s type in Python?
Use type(x) or isinstance(x, SomeType) to check. Convert with constructors like int(), float(), str(), list(), set(), and dict().
Where to go next
Continue your Python journey with more beginner-friendly lessons on our Python home page: CodDesire Python Tutorials.
Sources / Further reading
- Python 3.14.6 Documentation Index: https://docs.python.org/3.14/
- Built-in Types (standard type hierarchy): https://docs.python.org/3/library/stdtypes.html
- Assignment statements and annotated assignment: https://docs.python.org/3/reference/simple_stmts.html
- typing — Support for type hints: https://docs.python.org/3.14/library/typing.html
- PEP 526 — Variable Annotations: https://peps.python.org/pep-0526/
- PEP 695 — Type Parameter Syntax (generics): https://peps.python.org/pep-0695/


