Back to Python Notes
Topic #197

Variables and Data Types

By the end of this lesson, you will understand how Python variables store data and be able to identify and use the core built-in data types.

What it is

In Python, a variable is a name that refers to an object in memory. Unlike languages like C or Java, Python does not require you to declare a variable's type explicitly. Instead, Python uses dynamic typing: the type is determined at runtime based on the value assigned. Every piece of data in Python is an object, and variables are simply labels pointing to these objects.

The core immutable data types include int (integers), float (decimal numbers), str (text strings), and bool (True/False). The primary mutable collection types are list (ordered, changeable), tuple (ordered, unchangeable), set (unordered, unique items), and dict (key-value pairs).

Why it matters

  • Flexibility: You can write code faster without worrying about type declarations during development.
  • Data Structure Choice: Understanding types allows you to choose the right container for your data (e.g., using a set for fast lookups vs. a list for ordered storage).
  • Error Prevention: Knowing which types are mutable helps prevent bugs where unintended changes affect other parts of your program.
  • Interoperability: Correctly handling types ensures smooth interaction with libraries and APIs that expect specific data formats.

Syntax or steps

To create a variable, use the assignment operator =. The syntax is variable_name = value. Variable names must start with a letter or underscore, contain only alphanumeric characters and underscores, and cannot be reserved keywords.

  1. Choose a descriptive name for your variable.
  2. Assign a value using =.
  3. Use the type() function to verify the data type if needed.

Example

# Integer and Float
age = 30
price = 19.99

# String
name = "Alice"

# Boolean
is_active = True

# List (mutable, ordered)
fruits = ["apple", "banana", "cherry"]

# Tuple (immutable, ordered)
coordinates = (10.5, 20.3)

# Set (unique, unordered)
unique_ids = {101, 102, 103}

# Dictionary (key-value pairs)
person = {"name": "Bob", "age": 25}

print(type(age))      # <class 'int'>
print(fruits[0])      # apple
person["age"] = 26    # Updating dictionary value
print(person)

This example demonstrates creating variables of each core type. Note that lists and dictionaries allow modification after creation, while tuples do not. The print(type()) call confirms the inferred type.

Common mistakes

  • Assuming Static Typing: Reassigning a variable to a different type (e.g., x = 5 then x = "hello") is valid but can lead to confusing errors later if not handled carefully.
  • Mutating Default Arguments: Using a mutable list as a default argument in functions can cause unexpected state retention between calls.
  • Confusing Lists and Tuples: Trying to modify a tuple (e.g., t[0] = 1) raises a TypeError. Use lists if you need to change elements.
  • Unhashable Types in Sets/Dict Keys: You cannot use lists or dictionaries as keys in a dictionary or elements in a set because they are mutable and unhashable.

When to use it

Choosing the right data type depends on whether your data needs to be ordered, unique, or modifiable.

TypeOrdered?Mutable?Best For
listYesYesCollections that change size or content.
tupleYesNoFixed records, e.g., coordinates or RGB values.
setNoYesRemoving duplicates or membership testing.
dictYes*YesMapping keys to values for quick lookup.

*Note: Dictionaries maintain insertion order in Python 3.7+.

Practice

Guided Exercise: Create a dictionary representing a book with keys "title", "author", and "pages". Print the author's name.

Challenge: Convert the list [1, 2, 2, 3, 4, 4] into a set to remove duplicates, then convert it back to a sorted list.

Hint: Use set() and sorted() functions.

Quick check

Question: What happens if you try to assign a new value to an index in a tuple?

Answer: Python raises a TypeError because tuples are immutable.

Summary

Python variables are dynamic references to objects, allowing flexible coding styles. Mastering the distinction between mutable types like lists and dicts versus immutable types like tuples and strings is crucial for writing robust and efficient Python programs.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Variables and Data Types – FAQs

Quick answers about learning Variables and Data Types in Python.

This free note from Coding Now Tech Institute explains Variables and Data Types in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including Variables and Data Types, is 100% free with no signup required.
With focused practice, most students grasp Variables and Data Types in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now