Collections
Lists, dicts, and functional operations
Introduction
In this lesson, you'll learn about collections in Python. Coming from Java, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Java, you're familiar with lists, dicts, and functional operations.
Python has its own approach to lists, dicts, and functional operations, which we'll explore step by step.
The Python Way
Let's see how Python handles this concept. Here's a typical example:
nums = [1, 2, 3, 4, 5]
nums.append(6)
ages = {"Alice": 30, "Bob": 25}
val = ages.get("Alice", 0)
# List comprehensions (cleaner than streams)
doubled = [n * 2 for n in nums]
evens = [n for n in nums if n % 2 == 0]
total = sum(nums)
# Functional style
doubled2 = list(map(lambda n: n * 2, nums))
evens2 = list(filter(lambda n: n % 2 == 0, nums))
# Dict comprehension
square_map = {n: n**2 for n in range(6)}Comparing to Java
Here's how you might have written similar code in Java:
import java.util.*;
import java.util.stream.*;
List<Integer> nums = new ArrayList<>(Arrays.asList(1,2,3,4,5));
nums.add(6);
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
int val = ages.getOrDefault("Alice", 0);
// Stream API
List<Integer> doubled = nums.stream()
.map(n -> n * 2)
.collect(Collectors.toList());
List<Integer> evens = nums.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
int total = nums.stream().mapToInt(i->i).sum();You may be used to different syntax or behavior.
Python list replaces ArrayList; no type parameter needed
You may be used to different syntax or behavior.
Python dict replaces HashMap; simpler syntax
You may be used to different syntax or behavior.
Python list comprehensions replace Java Stream API
You may be used to different syntax or behavior.
Python sum(), min(), max() are built-in; Java needs stream().sum()
Step-by-Step Breakdown
1. Lists vs ArrayList
Python's built-in list is dynamic and needs no imports. No generics — the list holds any type.
List<Integer> nums = new ArrayList<>(Arrays.asList(1,2,3));nums = [1, 2, 3]2. Comprehensions vs Streams
Python list comprehensions are more concise than Java Streams and avoid the .collect(Collectors.toList()) boilerplate.
nums.stream().map(n -> n*2).collect(Collectors.toList())[n * 2 for n in nums]3. Built-in Aggregates
Python has sum(), min(), max(), len() as built-in functions. No stream needed.
nums.stream().mapToInt(i->i).sum()sum(nums)Common Mistakes
When coming from Java, developers often make these mistakes:
- Python list replaces ArrayList; no type parameter needed
- Python dict replaces HashMap; simpler syntax
- Python list comprehensions replace Java Stream API
Key Takeaways
- ArrayList → list (no imports, no generics)
- HashMap → dict
- Stream API → list comprehensions
- sum/min/max/len are built-in functions