You need to understand data types. Everything in Python is an object, and every object has a type. This decides what you can do with it. Let's get to it.
What is a Data Type?
Data types are the classifications that tell a programming language what kind of data is being stored or used, and what operations can be performed on it.
Primitive Types (The Basics)
These are your building blocks.
- Integers (int): Whole numbers. Positive, negative, or zero. No decimals.
x = 10
y = -300
- Floats (float): Numbers with a decimal point.
pi = 3.14
price = 99.99
- Strings (str): Text. Anything inside single (') or double (") quotes.
name = "John Doe"
error_message = 'File not found'
- Booleans (bool): Represents True or False. Used for conditions.
is_active = True
game_over = False
Collection Types (Storing Groups of Data)
You'll use these all the time.
- Lists (list): An ordered collection of items. You can change it (it's mutable). Items can be of different types. Defined with square brackets [].
my_list = [1, "hello", 3.14, True]
Access items by index: my_list[0]
gives you 1.
Change items: my_list[1] = "world"
- Tuples (tuple): An ordered collection of items. You cannot change it (it's immutable). Defined with parentheses ().
my_tuple = (1, "hello", 3.14)
Use it for data you know shouldn't change, like coordinates (x, y). Faster than lists.
- Dictionaries (dict): A collection of key-value pairs. Unordered (in older Python versions), but now ordered by insertion. Each key must be unique. Defined with curly braces {}.
my_dict = {"name": "Alice", "age": 30, "is_student": False}
Access values by key: my_dict["name"]
gives you "Alice".
Super useful for structured data, like JSON.
- Sets (set): An unordered collection of unique items. No duplicates. Defined with curly braces {} but not with key-value pairs.
my_set = {1, 2, 3, 3, 4}
The set will be {1, 2, 3, 4}
. Duplicates are automatically removed.
Good for membership testing (is 'apple' in my_fruit_set?) and mathematical set operations (union, intersection).
The "Nothing" Type
- NoneType (None): Represents the absence of a value. It's not 0, False, or an empty string. It's just... nothing.
my_variable = None
Functions that don't explicitly return anything will return None
.
Why This Matters
- Correct Operations: You can't add a string to an integer ("hello" + 5 will error). Knowing the type prevents errors.
- Memory and Performance: Different types use different amounts of memory. A tuple is lighter than a list.
- Data Structures: Choosing the right collection type (list vs. dict vs. set) is critical for writing efficient and readable code.
That's it. Know these, and you'll understand what's happening in your code. Don't overthink it.