Python Variables and Data Types with Examples

Python Variables and Data Types with Examples


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.

Key takeaways: Python variables and data types with examples

  • 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/set are mutable; int/str/tuple are immutable.
  • Inspect with type()/isinstance(); convert with int(), 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 is instead of ==.

What is a variable in Python?

Illustration of Python variables and data types with examples: int, float, string, bool, list, tuple, dict, set
Beginner-friendly view of Python variables mapped to core data types

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.

x = 10 # x points to an int
y = "Hello" # y points to a str
x = "Now text" # rebinding x to a new object (a str)
print(type(x), type(y))
Output
<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.
a = 5
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)
Output
10 [20, 30, 40] 50

Python variable rules and naming examples

  • Names may include letters, digits, and underscores, but can’t start with a digit: total_score, _hidden, name2 are fine; 2name is not.
  • Python is case-sensitive: Score and score are different.
  • Use snake_case for readability: average_speed.
  • Don’t use keywords like class or for as names.
  • Avoid shadowing built-ins like list or dict.
student_name = "Riya"
total_marks = 460
max_marks = 500
percentage = (total_marks / max_marks) * 100
print(student_name, round(percentage, 2))
Output
Riya 92.0

Do 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.

Code
age: int = 18
greeting: str = "Welcome"
valid: bool = True

Tip: 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

Visual of Python mutability vs immutability and type casting between data types
Mutability concepts and common type casting in Python, at a glance

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)

a = 7 # int
b = 2.5 # float
c = a + b
is_pass = True # bool (True/False)
print(a, b, c, is_pass)
Output
7 2.5 9.5 True
# Conversions
print(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

s = "café"
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 = [1, 2, 3] # list (mutable)
nums.append(4)
print(nums)

point = (10, 20) # tuple (immutable)
print(point[0], point[1])
Output
[1, 2, 3, 4]
10 20

Dictionaries (dict)

Dictionaries map keys to values. In modern Python, dicts preserve insertion order.

student = {"name": "Riya", "age": 19}
student["grade"] = "A"
print(student)

# Merge dicts
extra = {"roll": 23}
merged = student | extra
print(merged)
Output
{'name': 'Riya', 'age': 19, 'grade': 'A'}
{'name': 'Riya', 'age': 19, 'grade': 'A', 'roll': 23}

Sets

unique_marks = {90, 85, 90, 80}
print(unique_marks) # duplicates removed
passed = {80, 85, 90}
honors = {90, 95}
print(passed & honors) # intersection
Output
{80, 85, 90}
{90}

None

result = None
if result is None:
print("No result yet")
Output
No result yet

Mutable 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
# Immutable example
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
Output
6 5
[1, 2, 3] [1, 2, 3]

To avoid side effects with mutable types, copy them:

orig = [1, 2, 3]
copy_list = orig.copy() # or list(orig)
orig.append(4)
print(orig, copy_list)
Output
[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: bytes or bytearray
  • “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.

Code
value = [1, 2, 3]
print(type(value))                 # <class 'list'>
print(isinstance(value, list))     # True
print(isinstance(value, (list, tuple)))  # True if list or tuple

From input to correctly typed variable (flow)

1) Get raw data

input(), file read, API
raw = input()
Usually a str

2) Validate

Check format/range
raw.isdigit()
try: int(raw)

3) Convert

Use constructors
age = int(raw)
price = float(x)
data = dict(pairs)

4) Store clearly

Good names + hints
age: int = age
tags: set[str] = set(lst)

5) Use safely

Type‑appropriate ops
total += age
“py” in tags
student[“name”]

6) Output

Format back to text
print(f”Age: {age}”)
str(value)

Converting between data types (casting)

# Strings to numbers
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))
Output
['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.
Code
# 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 += 1
Output
12
first
second

Common 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 is instead 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 with try/except.
  • ✓ Prefer f-strings for output; avoid concatenating different types without str().
  • ✓ Use == for value equality, is for identity and is None checks.
  • ✓ Copy mutable containers (.copy() or list(x)/dict(x)) when sharing would cause side effects.
  • ✓ Use set for uniqueness and fast membership, dict for labeled records, tuple for fixed-size groups.
  • ✓ For money, consider decimal.Decimal; for JSON data, use dict/list with the json module.

Quick practice

  1. Create variables for your name (str), age (int), and GPA (float). Print them in one sentence using an f-string.
  2. Given scores = [88, 92, 75, 92], convert to a set to remove duplicates, then back to a sorted list.
  3. Make a dict person with keys name, skills (list), and active (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

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted