Welcome back! In our first lesson, we successfully set up your Python development environment. You now have an isolated workspace ready for any project, complete with package and dependency management using venv and pip. This foundational setup is the professional standard and will serve you well as we move from infrastructure to implementation.
This lesson bridges the gap between your existing programming knowledge and Python's specific syntax. We will focus on two of Python's most fundamental data structures: lists and dictionaries. We'll also cover how to write functions to organize your code and operate on these structures. For someone with your extensive background in PHP, this will involve mapping concepts you already know, like indexed and associative arrays, to their Python equivalents. By the end of this lesson, you will be able to write Python functions that create, manipulate, and return these core data structures, equipping you with the essential tools to start building more complex logic.
From PHP Arrays to Python Lists and Dictionaries
One of the most significant initial differences for a PHP developer moving to Python is how arrays are handled. In PHP, the array type is a powerful, all-in-one structure that can be used as an ordered, indexed list, an associative map (key-value pairs), or even a mix of both. Python takes a more explicit approach, splitting this functionality into two distinct and optimized types:
- Lists: These are ordered sequences of elements, analogous to PHP's indexed arrays.
- Dictionaries: These are unordered collections of key-value pairs, analogous to PHP's associative arrays.
This separation provides clarity and performance benefits. To see this comparison directly, let's start with a resource created for developers making the exact transition you are.
Transitioning from PHP to Python: A Comprehensive Guide ...
This guide directly compares PHP's array syntax with Python's list and dictionary syntax, which will help you map your existing knowledge to the new language.
Please read the section titled Arrays vs. Lists and Dictionaries. Pay close attention to how the single array concept in PHP is split into list (using []) and dictionary (using {}) in Python.
Working with Lists
As you just read, a Python list is an ordered, mutable (changeable) collection of items. Let's dive deeper into how to work with them. The following video gives a great tour of lists and their capabilities.
Python lists, sets, and tuples explained 🍍
This video from Bro Code provides a clear and practical demonstration of how to create, access, and manipulate Python lists.
Please watch the following segments: Creating and iterating: This covers list creation, accessing elements by index (e.g., fruits[0]), and looping through a list. Useful functions: This shows how to find the length of a list with len() and check for an element's existence with the in keyword. Common list methods: This demonstrates core methods like .append(), .remove(), .insert(), and .sort().
To summarize the key list operations you'll use most often:
- Create a list:
my_list = [1, "hello", 3.14] - Access an element:
first_item = my_list[0] - Get the length:
num_items = len(my_list) - Add an element to the end:
my_list.append("world") - Remove an element by value:
my_list.remove("hello") - Iterate through elements:
for item in my_list: print(item)
Working with Dictionaries
Dictionaries store data in key-value pairs. They are incredibly useful for structuring data, much like you would with an associative array in PHP or a JSON object.
Here's how you work with them:
- Create a dictionary:
# A dictionary representing a user user = { "username": "alex", "email": "alex@example.com", "login_count": 5 } - Access a value by its key:
print(user["email"]) # Outputs: alex@example.com - Add or update a key-value pair:
user["login_count"] = 6 # Updates the value for an existing key user["last_login"] = "2023-10-27" # Adds a new key-value pair - Iterate through a dictionary: You can loop through its keys, values, or both.
# Iterate through keys for key in user.keys(): print(f"Key: {key}, Value: {user[key]}") # A more direct way to iterate through key-value pairs for key, value in user.items(): print(f"Key: {key}, Value: {value}")
A very common and powerful pattern in Python is creating a list of dictionaries. This is how you'll often handle structured records, such as data retrieved from a database or an API.

Encapsulating Logic with Functions
As in any language, functions are the building blocks for organizing and reusing code. Your experience with PHP functions will translate directly. The syntax in Python, however, relies on the def keyword and indentation rather than curly braces.
Let's explore how to define and use functions in Python, especially how they interact with the data structures we've just learned.
24. Functions | Python Tutorial
This tutorial covers the syntax for defining functions and explains how they handle parameters and return values.
Start by reading the section Functions in Python. This will introduce you to the basic def and return syntax. Next, read Returning Multiple Values. This section highlights a convenient Python feature where you can return multiple items from a function, which Python automatically packs into a data structure called a tuple. A tuple is similar to a list but is immutable (cannot be changed after creation).
Advanced Function Arguments
Python offers flexible ways to handle function arguments, which are especially useful when working with lists and dictionaries.
*args: To accept an arbitrary number of positional arguments, which are collected into a tuple.**kwargs: To accept an arbitrary number of keyword arguments, which are collected into a dictionary.
This pattern is ubiquitous in Python frameworks, so understanding it is crucial.
24. Functions | Python Tutorial
This part of the tutorial explains the *args and **kwargs syntax.
Please read the sections Arbitrary Number of Parameters and Arbitrary Number of Keyword Parameters. Focus on how *values collects arguments into a tuple and **kwargs collects them into a dictionary.
A Critical Python Pitfall: Mutable Default Arguments
There is a classic "gotcha" in Python that trips up many developers, and it relates directly to using lists and dictionaries as default arguments in functions. Because default arguments are evaluated only once (when the function is defined), using a mutable type like a list or dictionary can lead to unexpected behavior across multiple function calls.
24. Functions | Python Tutorial
This section explains a common but tricky aspect of Python functions. Understanding this will save you from future debugging headaches.
Read the section The Defaults Pitfall. The key takeaway is the correct pattern for initializing a default list or dictionary: set the default to None and then create the new list/dictionary inside the function.
Your Turn: Putting It All Together
Now it's time to apply what you've learned. Let's write a function that works with a list of dictionaries.
Task: Complete the following Python function. It should take a list of people (in the same format as the people image) and an integer min_age. The function should return a new list containing the names of all people who are older than min_age.
Starter Code:
# Here is our list of dictionaries
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35},
{"name": "Diana", "age": 28}
]
def find_people_older_than(user_list, min_age):
# Create an empty list to store the names
names = []
# --- YOUR CODE GOES HERE ---
# Loop through each person (dictionary) in the user_list.
# Check if the person's 'age' is greater than min_age.
# If it is, append their 'name' to the 'names' list.
# ---------------------------
# Return the list of names
return names
# --- Example Usage ---
# Let's find everyone older than 29
older_people_names = find_people_older_than(people, 29)
print(older_people_names) # Expected output: ['Alice', 'Charlie']
# Let's find everyone older than 32
older_people_names_2 = find_people_older_than(people, 32)
print(older_people_names_2) # Expected output: ['Charlie']
Click here to see the solution
# Here is our list of dictionaries
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35},
{"name": "Diana", "age": 28}
]
def find_people_older_than(user_list, min_age):
# Create an empty list to store the names
names = []
# Loop through each person (dictionary) in the user_list.
for person in user_list:
# Check if the person's 'age' is greater than min_age.
if person["age"] > min_age:
# If it is, append their 'name' to the 'names' list.
names.append(person["name"])
# Return the list of names
return names
# --- Example Usage ---
# Let's find everyone older than 29
older_people_names = find_people_older_than(people, 29)
print(older_people_names)
# Let's find everyone older than 32
older_people_names_2 = find_people_older_than(people, 32)
print(older_people_names_2)
Conclusion
In this lesson, you've mastered the building blocks of Python programming. You can now confidently work with Python's primary data structures and organize your logic within functions.
Key Takeaways:
- Python separates PHP's versatile
arrayinto lists (for ordered, indexed data) and dictionaries (for unordered, key-value data). - Functions are defined with
defand use indentation to define scope. They can handle lists and dictionaries as arguments and return them as results. - Python functions can accept a variable number of arguments using
*args(which creates a tuple) and**kwargs(which creates a dictionary). - A critical best practice is to avoid using mutable types like lists or dictionaries as default function arguments to prevent unintended side effects.
You are now well-prepared for our next topic: interacting with the outside world. In the next lesson, we will learn how to parse JSON data and make authenticated HTTP requests to an API. You will see immediately how the lists and dictionaries you learned about today are the natural way to handle the structured data that APIs provide.