It's easy to forget about the basic operations of Python lists, tuples, dictionaries, and sets. Behavior in Python 3.x series.
is mutable?
list | Tuple | dictionary | set |
---|---|---|---|
Yes | No | Yes | Yes |
operation | list | Tuple | dictionary | set |
---|---|---|---|---|
Generate empty collection | list() [ ] |
tuple() ( ) |
dict() { } |
set() |
literal | [0, 1] |
(0, 1) |
{'A': 0, 'B': 1} |
{0, 1} |
Duplicate(Shallow copy) | list(a) a.copy() a[:] |
tuple(a) Substitution |
dict(a) a.copy() |
set(a) a.copy() |
add to | a.append(val) |
- | a[key] = val |
a.add(val) |
Join(in-place) | a.extend(b) a += b |
- | a.update(b) |
a.update(b) a |= b |
Join(not-in-place) | a + b |
a + b |
- | a | b a.union(b) |
Join(starred expression[^starred]) | [*a, *b] |
(*a, *b) *a, *b |
{**a, **b} |
{*a, *b} |
Insert(Single element) | a.insert(idx, val) a[idx:idx] = val, |
- | - | - |
Insert(Multiple elements) | a[idx:idx] = b |
- | - | - |
Intersection | - | - | - | a & b a.intersection(b) |
Difference | - | - | - | a - b a.difference(b) |
Delete(Value specification) | a.remove(val) |
- | - | a.remove(val) |
Delete(Key specification) | del a[idx] del a[start:stop:step] |
- | del a[key] |
- |
Delete all | a.clear() del a[:] |
- | a.clear() |
a.clear() |
Element count | len(a) a.count() |
len(a) |
len(a) |
len(a) |
[^ starred]: Available from Python 3.5.