Skip to main content

Command Palette

Search for a command to run...

Python Data Structures Simplified for Laravel Developers

Updated
3 min read
Python Data Structures Simplified for Laravel Developers

Transitioning from PHP to Python for Machine Learning feels a bit like moving from a familiar manual car to an electric one. The controls are in similar places, but the way the engine feels under the hood is fundamentally different.

As Laravel developers, we are spoiled by the PHP array. It’s our everything tool.

Need a list? Array. Need a map? Array. Need a stack? Array.

Python, however, prefers specialized tools for specialized tasks. This is the secret to why it handles massive ML datasets so efficiently.

Here is your guide to mastering Python data structures without losing your Laravel mindset.


1. Lists: Your New Indexed Array

In Laravel, when you’re fetching a collection of names, you’re working with an indexed array. In Python, this is a List.

The PHP Way

$frameworks = ['Laravel', 'Symfony', 'CodeIgniter'];
$frameworks[] = 'Lumen'; // Push to end
echo $frameworks[0];     // Laravel

The Python Way

frameworks = ['Laravel', 'Symfony', 'CodeIgniter']
frameworks.append('FastAPI') # Using a method instead of []
print(frameworks[0])         # Laravel

The ML Advantage: Slicing

In ML, you often need to "split" your data (e.g., take the first 80% for training). Python makes this incredibly easy compared to array_slice().

# Python "Slicing" syntax: [start:stop]
top_two = frameworks[:2]  # ['Laravel', 'Symfony']
last_one = frameworks[-1] # 'FastAPI' (Negative indexing is a lifesaver!)

2. Dicts: The Associative Array

When you’re defining an $user object in a controller, you use an associative array. In Python, we call this a Dictionary (or Dict).

The PHP Way

$config = [
    'driver' => 'mysql',
    'host' => '127.0.0.1'
];
$driver = $config['driver'];
$port = $config['port'] ?? 3306; // Null coalesce

The Python Way

config = {
    'driver': 'mysql',
    'host': '127.0.0.1'
}
driver = config['driver']
port = config.get('port', 3306) # The "get" method handles missing keys gracefully

The Human Touch: In Python, keys are typically strings or numbers. You’ll use these constantly in ML to hold Hyperparameters the settings for your models (like {'learning_rate': 0.01, 'epochs': 10}).


3. Tuples: The One You’re Missing

This is the one structure that doesn't have a twin in PHP. A Tuple is essentially an array that cannot be changed once it's born (it's "immutable").

Why would you want that?

Imagine you have an RGB color for a brand or geographic coordinates for a store. You don't want your code to accidentally change the Latitude halfway through a calculation.

# Defined with parentheses
coordinates = (34.0522, -118.2437)

# This will throw an error! 
# coordinates[0] = 35.0

Pythonic "Unpacking":

You know how we use list() or [] In PHP, to destructure? Python does this natively and beautifully.

// PHP Destructuring
[$lat, $long] = [34.0522, -118.2437];
# Python Unpacking
lat, long = coordinates
print(f"Lat: {lat}, Long: {long}")

The "Laravel to Python" Cheat Sheet

TaskLaravel (PHP)Python
Count itemscount($items)len(items)
Check for keyarray_key_exists('k', $arr)'k' in items
Merge dataarray_merge($a, $b){**a, **b} (for dicts)
Get all keysarray_keys($arr)items.keys()
Loopingforeach($arr as $k => $v)for k, v in items.items():

Exercise: The "Laravel Config" Challenge

To get these into your muscle memory, try this:

  1. Create a Dict named app_settings containing a name, env, and a List of providers.

  2. Add a new provider to the list.

  3. Use .get() to try to print a version key that doesn't exist yet, providing 1.0 as a default.

  4. Create a Tuple for your database credentials (host, port, user) and unpack them into three separate variables.

Laravel to ML

Part 2 of 3

Ready to go from Laravel to AI? This series bridges the gap for PHP devs. Learn essential Python, master tools like Pandas & Scikit-learn, and understand core ML models. Leverage your backend skills to build intelligent applications today.

Up next

Laravel to ML Roadmap

Think of this roadmap like a road you’re walking, not a course you’re rushing through. You start where you already are, building Laravel apps, handling requests, and working with data. The first few checkpoints are simple: Python basics and data hand...