Lists → Slices, Dicts → Maps
Core collection types
Introduction
In this lesson, you'll learn about lists → slices, dicts → maps in Go. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Python, you're familiar with core collection types.
Go has its own approach to core collection types, which we'll explore step by step.
The Go Way
Let's see how Go handles this concept. Here's a typical example:
package main
import "fmt"
// Slice (like Python list)
nums := []int{1, 2, 3}
nums = append(nums, 4)
sub := nums[1:3]
// Map (like Python dict)
ages := map[string]int{"Alice": 30, "Bob": 25}
ages["Charlie"] = 35
val, ok := ages["Alice"] // ok = false if missing
delete(ages, "Bob")
// No comprehensions — use loops
doubled := make([]int, len(nums))
for i, n := range nums {
doubled[i] = n * 2
}
// Range over map
for k, v := range ages {
fmt.Println(k, v)
}Comparing to Python
Here's how you might have written similar code in Python:
# List
nums = [1, 2, 3]
nums.append(4)
sub = nums[1:3]
# Dict
ages = {"Alice": 30, "Bob": 25}
ages["Charlie"] = 35
val = ages.get("Alice", 0)
del ages["Bob"]
# Comprehensions
doubled = [n * 2 for n in nums]
evens = {n for n in nums if n % 2 == 0}
# Tuple unpacking
for k, v in ages.items():
print(k, v)You may be used to different syntax or behavior.
Python list → Go slice; append works in both
You may be used to different syntax or behavior.
Python dict → Go map[K]V; access returns (value, ok) in Go
You may be used to different syntax or behavior.
Go has no list/dict comprehensions — use loops
You may be used to different syntax or behavior.
Go delete(m, k) → Python del d[k]
Step-by-Step Breakdown
1. Slices
Go slices work like Python lists — dynamic, with append and slicing. The syntax is almost identical.
nums.append(4); sub = nums[1:3]nums = append(nums, 4); sub := nums[1:3]2. Map Access
Go map access returns a second bool indicating if the key existed. Python's dict.get(key, default) has a different idiom.
val = ages.get("Alice", 0)val, ok := ages["Alice"]
if !ok { val = 0 }3. No Comprehensions
Go has no list comprehensions. Write explicit for loops — they're clearer in Go's style.
doubled = [n * 2 for n in nums]doubled := make([]int, len(nums))
for i, n := range nums { doubled[i] = n * 2 }Common Mistakes
When coming from Python, developers often make these mistakes:
- Python list → Go slice; append works in both
- Python dict → Go map[K]V; access returns (value, ok) in Go
- Go has no list/dict comprehensions — use loops
Key Takeaways
- Python list → Go slice; append works the same
- Python dict → Go map[K]V
- Map access: val, ok := m[key]
- No comprehensions — use range loops