Python list and dict vs Java ArrayList and HashMap

Python's collections are built into the language, with their own literal syntax. Here is every ArrayList, HashMap and HashSet method you use daily, mapped to its Python form, plus slicing, tuples and the list-of-dicts shape that carries all JSON and AI data.

Left, a Java sheet tagged 6 lines: List of String models equals new ArrayList, models.add small, then Map of String to String user equals new HashMap, user.put name Asha. An arrow points right to a yellow Python sheet tagged 4 lines: models equals a list literal, user equals a dict literal, tags equals a set literal, point equals a tuple. Caption: list, dict, set, tuple: no imports, no new.
Fig. 1 — Four built-in collections, each with its own literal. No imports, no generics, no new.

In Java, before you can store two strings in a list, you import java.util.List and java.util.ArrayList, pick a generic type and call new. In Python you write ["a", "b"]. That’s it.

Python has four built-in collections, each with its own literal syntax. Two of them, list and dict, carry almost all the data you’ll meet: API responses, chat messages, search results, config. This article maps the Java methods you already use to their Python forms.

This is part 4 of Python for Java Developers. Part 3 covered for loops with range, enumerate and zip, which you’ll use on every collection below.

The four collections

Python Literal Closest Java Use it for
list [1, 2, 3] ArrayList An ordered sequence you change
dict {"name": "Asha"} LinkedHashMap Key to value lookups
set {1, 2, 3} HashSet Unique values, fast membership
tuple (1, 2) a small record A fixed group of values

No generics: a list can hold mixed types. In practice, keep one type per list, and use a type hint like list[str] when you want to document it (type hints get their own part later in the series).

list: Python’s ArrayList

List<String> models = new ArrayList<>(List.of("small", "medium"));
models.add("large");
String first = models.get(0);
int n = models.size();
boolean has = models.contains("medium");
models = ["small", "medium"]
models.append("large")
first = models[0]
n = len(models)
has = "medium" in models

The methods you’ll reach for, side by side:

Java ArrayList Python list
list.add(x) items.append(x)
list.add(i, x) items.insert(i, x)
list.addAll(other) items.extend(other) or items + other
list.get(i) items[i]
list.get(list.size() - 1) items[-1]
list.set(i, x) items[i] = x
list.remove(i) (by index) items.pop(i) (returns it)
list.remove(x) (by value) items.remove(x)
list.contains(x) x in items
list.indexOf(x) items.index(x) (raises if missing)
list.size() len(items)
list.isEmpty() not items
list.clear() items.clear()
Collections.sort(list) items.sort()
Collections.reverse(list) items.reverse()

Negative indexes count from the end: items[-1] is the last item, items[-2] the one before it.

Slicing: subList on steroids

Slicing cuts a piece out of any list, string or tuple: items[start:stop]. The stop index is excluded, and either side can be left out.

nums = [10, 20, 30, 40, 50]
nums[1:3]     # [20, 30]          like subList(1, 3)
nums[:2]      # [10, 20]          first two
nums[-2:]     # [40, 50]          last two
nums[::2]     # [10, 30, 50]      every second item
nums[::-1]    # [50, 40, 30, 20, 10]  reversed copy
nums[:]       # a shallow copy of the whole list

Unlike subList, a slice is a new list, not a view. Changing it doesn’t touch the original. You’ll see history[-10:] to keep the last ten chat messages, and text[:500] to trim long input.

dict: Python’s HashMap

Map<String, String> user = new HashMap<>();
user.put("name", "Asha");
user.put("plan", "pro");
String plan = user.get("plan");
String email = user.getOrDefault("email", "unknown");
user = {"name": "Asha", "plan": "pro"}
plan = user["plan"]
email = user.get("email", "unknown")
Java HashMap Python dict
map.put(k, v) d[k] = v
map.get(k) d[k] (raises KeyError if missing) or d.get(k) (gives None)
map.getOrDefault(k, v) d.get(k, v)
map.containsKey(k) k in d
map.remove(k) d.pop(k) or del d[k]
map.putIfAbsent(k, v) d.setdefault(k, v)
map.putAll(other) d.update(other) or d | other (new dict)
map.keySet() d.keys()
map.values() d.values()
map.entrySet() d.items()
map.size() len(d)

Loop over keys and values together with .items():

for key, value in user.items():
    print(key, value)

Two differences from HashMap worth knowing: a dict keeps insertion order (like LinkedHashMap), and keys must be immutable values such as strings, numbers or tuples. A list can’t be a key.

Counting and grouping

The classic Java interview exercise, counting words with merge or getOrDefault, has a one-line answer in Python’s standard library:

from collections import Counter, defaultdict

counts = Counter(text.split())          # {"the": 12, "java": 3, ...}
counts.most_common(3)                   # top 3 as (word, count) pairs

by_length = defaultdict(list)           # missing keys start as []
for word in words:
    by_length[len(word)].append(word)

Counter is a dict that counts; defaultdict creates a default value for a missing key, like computeIfAbsent.

set: unique values

tags = {"ai", "java", "ai"}     # {"ai", "java"}  duplicates dropped
unique_ids = set(ids)           # remove duplicates from a list
"ai" in tags                    # fast membership test

a = {1, 2, 3}
b = {2, 3, 4}
a | b     # {1, 2, 3, 4}   union         (Java: addAll)
a & b     # {2, 3}         intersection  (Java: retainAll)
a - b     # {1}            difference    (Java: removeAll)

One trap: {} is an empty dict, not an empty set. Write set() for an empty set.

tuple and unpacking

A tuple is a fixed group of values in round brackets. You can’t change it after it’s made. Its real power is unpacking, assigning its parts to names in one line:

point = (3, 4)
x, y = point

def min_max(nums):
    return min(nums), max(nums)     # returns a tuple

low, high = min_max([4, 1, 9])

This is how a Python function “returns two things”. In Java you’d create a small record; in Python, you return a tuple and unpack it.

Sorting

list.sort() sorts in place and returns None. sorted() returns a new list and works on anything iterable. Both take a key function, Python’s Comparator.comparing:

employees.sort(Comparator.comparing(Employee::salary).reversed());
employees.sort(key=lambda e: e.salary, reverse=True)
ranked = sorted(hits, key=lambda h: h["score"], reverse=True)

The shape of all JSON: a list of dicts

Look at this. It’s the most important data shape in Python code:

messages = [
    {"role": "system", "content": "You are concise."},
    {"role": "user", "content": "What is RAG?"},
]

A list of dicts. Chat history, search results, API responses and config files all look like this, because JSON maps almost one to one onto Python: object becomes dict, array becomes list, null becomes None.

import json

data = json.loads('{"score": 0.92, "tags": ["ai"]}')   # JSON text -> dict
data["tags"][0]                                        # "ai"
text = json.dumps(data, indent=2)                      # dict -> JSON text

No Jackson, no POJO, no TypeReference. When you want types and validation on top, Python developers reach for Pydantic, covered in the classes part of this series.

Traps for Java developers

  • b = a doesn’t copy. Both names point to the same list, just like Java references. Use a.copy(), list(a) or a[:]. For nested data (a list of dicts), use copy.deepcopy(a).
  • items = items.sort() sets items to None, because sort() returns nothing. Use items.sort() alone, or items = sorted(items).
  • d[key] on a missing key raises KeyError. Use d.get(key) when the key might not be there.
  • {} is a dict. An empty set is set().
  • Removing items while looping over the same list skips elements. Build a new list instead.

Key takeaways

  • list, dict, set and tuple are built in, with [], {}, {1, 2} and () literals.
  • append, len(), in and [i] cover most ArrayList work; [-1] is the last item.
  • Slices like items[1:3] and items[-10:] return new lists.
  • d.get(key, default) is getOrDefault; .items() is entrySet(); dicts keep insertion order.
  • Functions return several values as a tuple you unpack: low, high = min_max(nums).
  • JSON is a list of dicts, and json.loads / json.dumps convert it.

Frequently asked questions

What is the Python equivalent of a Java ArrayList?

list. Create one with [] or ["a", "b"], add with append(), read with items[i], and get the size with len(items).

What is the Python equivalent of a Java HashMap?

dict. Create one with {} or {"key": "value"}, write with d[key] = value, and read safely with d.get(key). A dict also keeps insertion order, like a LinkedHashMap.

What is the difference between a list and a tuple in Python?

A list can change after it’s created; a tuple can’t. Use a list for a collection that grows, and a tuple for a fixed group of values, such as a pair of coordinates or two return values.

How do I copy a list in Python?

new = old.copy(), list(old) or old[:] make a shallow copy. For lists that contain other lists or dicts, use copy.deepcopy(old) so the inner objects are copied too.

What does slicing mean in Python?

Slicing takes a piece of a list, string or tuple with items[start:stop:step]. The stop index is excluded, negative numbers count from the end, and the result is a new object.

Next in the series: Python functions, default and keyword arguments, and why Python doesn’t need method overloading or builders.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.