Arrays → Lists
Storing sequences of data
Introduction
In this lesson, you'll learn about arrays → lists in Python. Coming from C, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In C, you're familiar with storing sequences of data.
Python has its own approach to storing sequences of data, which we'll explore step by step.
The Python Way
Let's see how Python handles this concept. Here's a typical example:
# Dynamic list — grows automatically
nums = [1, 2, 3, 4, 5]
n = len(nums)
# Append and extend
nums.append(6)
nums.extend([7, 8])
# Iteration
for num in nums:
print(num)
# Slicing
sub = nums[1:4] # [2, 3, 4]
rev = nums[::-1] # reversed
# List comprehension
squares = [x**2 for x in range(10)]
# 2D list
matrix = [[1,2,3],[4,5,6],[7,8,9]]Comparing to C
Here's how you might have written similar code in C:
#include <stdio.h>
#include <string.h>
/* Fixed-size array */
int nums[5] = {1, 2, 3, 4, 5};
int n = sizeof(nums) / sizeof(nums[0]); /* length */
/* Iteration */
for (int i = 0; i < n; i++) {
printf("%d\n", nums[i]);
}
/* 2D array */
int matrix[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
/* No built-in dynamic array — use malloc */
int *dyn = malloc(10 * sizeof(int));
dyn[0] = 42;
free(dyn);You may be used to different syntax or behavior.
C arrays are fixed-size; Python lists are dynamic
You may be used to different syntax or behavior.
C arrays need sizeof tricks for length; Python uses len()
You may be used to different syntax or behavior.
No malloc/free in Python — garbage collector handles memory
You may be used to different syntax or behavior.
Python lists support slicing, comprehensions, and mixed types
Step-by-Step Breakdown
1. Dynamic Size
C arrays are fixed at compile time. Python lists grow dynamically with append() — no malloc/free needed.
int nums[5] = {1, 2, 3, 4, 5};nums = [1, 2, 3, 4, 5]
nums.append(6) # grows automatically2. Slicing
Python's slice syntax nums[start:stop:step] is far more powerful than C's manual index calculations.
nums[1:4] # elements 1,2,3
nums[::-1] # reversed copy
nums[::2] # every other element3. List Comprehensions
Python list comprehensions replace C's for-loop-with-array patterns with a single expressive line.
int squares[10];
for (int i = 0; i < 10; i++) squares[i] = i*i;squares = [i**2 for i in range(10)]Common Mistakes
When coming from C, developers often make these mistakes:
- C arrays are fixed-size; Python lists are dynamic
- C arrays need sizeof tricks for length; Python uses len()
- No malloc/free in Python — garbage collector handles memory
Key Takeaways
- Fixed-size C arrays → dynamic Python lists
- malloc/free → no manual memory management
- sizeof tricks → len()
- Python slicing and comprehensions have no C equivalent