No history yet

Data Types

The Building Blocks of Data

In Python, every piece of data has a type. A data type is just a category that tells the computer how to store and work with a value. Is it a number? A piece of text? A collection of other items? Knowing the type is essential.

Python figures out these types for you automatically, a feature called dynamic typing. You don't have to declare a variable's type beforehand. You can just assign a value, and Python handles the rest.

Numbers and Text

The most fundamental data types handle numbers and text. Python has two main types for numbers: integers and floating-point numbers.

integer

noun

A whole number, positive or negative, without a fractional part.

Integers, or int, are for whole numbers. Floats, or float, are for numbers with a decimal point. Basic arithmetic operations work just as you'd expect.

whole_number = 100         # This is an int
decimal_number = 25.5      # This is a float

# Basic arithmetic
sum_result = whole_number + decimal_number
print(sum_result)            # Output: 125.5

For text, Python uses strings, or str. You can create a string using either single (') or double (") quotes. They are sequences of characters.

greeting = "Hello, World!"
name = 'Alice'

# You can combine strings using the + operator
full_greeting = greeting + " My name is " + name + "."
print(full_greeting)
# Output: Hello, World! My name is Alice.

Grouping Your Data

Often, you need to store collections of data. Python provides several powerful built-in data types for this, each with its own strengths.

Lists and Tuples

Lists and tuples are both ordered sequences, meaning the items have a defined position. The key difference is mutability. Lists are mutable (changeable), while tuples are immutable (unchangeable).

Think of a list as a shopping list: you can add, remove, or change items. A tuple is more like a set of coordinates: once defined, it shouldn't change.

# A list is created with square brackets []
my_list = [1, "apple", 3.14]
print(my_list[1])  # Access by index -> "apple"

my_list[1] = "orange" # Lists are mutable
print(my_list)     # Output: [1, 'orange', 3.14]

# A tuple is created with parentheses ()
my_tuple = (1, "apple", 3.14)
print(my_tuple[0]) # Access by index -> 1

# This would cause an error, because tuples are immutable
# my_tuple[0] = 99

Sets and Dictionaries

Sets and dictionaries are unordered collections.

A set is a collection of unique items. If you add a duplicate item to a set, it will be ignored. They are useful for membership testing and removing duplicates from a sequence.

# A set is created with curly braces {}
my_set = {1, 2, 3, 3, 4, 2}
print(my_set) # Output: {1, 2, 3, 4}

# Check for membership
print(3 in my_set) # Output: True

A dictionary, or dict, stores data in key-value pairs. Instead of being indexed by position, you look up a value by its associated key. This makes them incredibly fast for retrieving data when you know the key.

# A dictionary uses curly braces with key:value pairs
contact = {
    "name": "Alice",
    "phone": "555-1234",
    "email": "alice@example.com"
}

# Access a value by its key
print(contact["phone"]) # Output: 555-1234
Data TypeSyntaxOrdered?Mutable?Use Case
list[1, 2, 3]YesYesA general-purpose, changeable sequence.
tuple(1, 2, 3)YesNoData that should not be modified.
set{1, 2, 3}NoYesStoring unique items; membership tests.
dict{'a': 1}No*YesStoring key-value pairs for fast lookup.

*As of Python 3.7+, dictionaries maintain insertion order, but you should still think of them as mappings rather than sequences.

Flexibility with Types

Python’s flexibility comes from two main features: dynamic typing and type conversion.

We mentioned dynamic typing earlier. It means you don’t have to declare a variable's type. A variable is just a name pointing to a value, and that name can point to different types of values during the program's execution.

my_variable = 10
print(type(my_variable)) # Output: <class 'int'>

my_variable = "Now I'm a string"
print(type(my_variable)) # Output: <class 'str'>

While convenient, this means you need to be mindful of what type of data your variable holds at any given time.

Sometimes, you need to explicitly convert a value from one type to another. This is called type conversion or type casting. For example, when you get input from a user, it always comes in as a string. If you want to treat it as a number, you must convert it.

# User input is always a string
age_string = "30"

# Convert the string to an integer to do math
age_number = int(age_string)
years_until_50 = 50 - age_number

print("You will be 50 in " + str(years_until_50) + " years.")
# The integer result must be converted back to a string for concatenation

Common conversion functions include int(), float(), str(), list(), and set(). You can convert between compatible types, but trying to convert an incompatible value, like int("hello"), will result in an error.

Ready to check your understanding?

Quiz Questions 1/6

What does it mean that Python is a "dynamically typed" language?

Quiz Questions 2/6

What is the primary difference between a list and a tuple in Python?

Understanding these fundamental data types is the first major step in mastering Python. They are the structures you will use to build every program.