= [47, 52, 71, 90]
li1 type(li1), len(li1) li1,
([47, 52, 71, 90], list, 4)
x = [1, 2, 3]
t = (1, 2, 3)
r = range(1, 11)
d = {"name": "Rasel", "dept": "ISRT"}
s = {1, 2, 3}
A list stores an ordered sequence of items. Create with square brackets:
= [47, 52, 71, 90]
li1 type(li1), len(li1) li1,
([47, 52, 71, 90], list, 4)
= [1, "a", [3, 4]]
li2 len(li2) li2,
([1, 'a', [3, 4]], 3)
47 in li1, 99 in li1
(True, False)
int
, float
, str
, list
).object.method(...)
.append
, extend
, insert
, pop
, sort
, clear
, copy
.24) # add a single item to the end
li1.append( li1
[47, 52, 71, 90, 24]
2, 100) # insert at index 2
li1.insert( li1
[47, 52, 100, 71, 90, 24]
1) # remove-and-return item at index 1
li1.pop( li1
[47, 100, 71, 90, 24]
append(x)
adds one element; extend(iterable)
adds many elements:= [4, None, "foo"]
x 7, 8, (2, 3)]) # concatenates elements from the iterable
x.extend([ x
[4, None, 'foo', 7, 8, (2, 3)]
4, None, "foo"] + [7, 8, (2, 3)] [
[4, None, 'foo', 7, 8, (2, 3)]
reverse=
and key=
:= [1, 2, 3, 31, 32, 33, 11, 12, 13]
a
a.sort() a
[1, 2, 3, 11, 12, 13, 31, 32, 33]
=True)
a.sort(reverse a
[33, 32, 31, 13, 12, 11, 3, 2, 1]
= ["alice", "Bob", "carol"]
names =str.lower) # case-insensitive sort
names.sort(key names
['alice', 'Bob', 'carol']
= [3, 1, 2]
b = sorted(b, reverse=True)
sorted_b b, sorted_b
([3, 1, 2], [3, 2, 1])
seq[start:stop]
returns a new list; start
inclusive, stop
exclusive.= [1, 2, 3, 41, 42, 43, 11, 12, 13]
seq 3:4], seq[3:5] seq[
([41], [41, 42])
start
or stop
to use defaults:5], seq[5:] seq[:
([1, 2, 3, 41, 42], [43, 11, 12, 13])
-4:], seq[-6:-2] seq[
([43, 11, 12, 13], [41, 42, 43, 11])
3:5] = [6, 3]
seq[ seq
[1, 2, 3, 6, 3, 43, 11, 12, 13]
seq[start:stop:step]
(can be negative):2], seq[::-1] # every 2nd; reversed copy seq[::
([1, 3, 3, 11, 13], [13, 12, 11, 43, 3, 6, 3, 2, 1])
R
.= 1947
a = a # both refer to the same int object (1947)
b = 1971 # a now refers to a new int object; b still 1947
a print(a, b)
1971 1947
= [1, 2, 3]
orig = orig # same object
alias 99)
orig.append( alias, orig
([1, 2, 3, 99], [1, 2, 3, 99])
int
, float
, bool
, str
) are immutable; when you “change” them, you are actually re-binding the name to a new object.list
are often mutable; mutation changes the object itself without re-binding the name.= [1, 2, 3]
orig = orig # same object
alias = orig[:] # new list (shallow copy) — or: orig.copy(), list(orig)
shallow 99)
orig.append( alias, shallow
([1, 2, 3, 99], [1, 2, 3])
A tuple is an immutable, ordered sequence.
= (4, 5, 6)
tup1 = 4, 5, 6 # parentheses optional in many contexts
tup2 tup1, tup2
((4, 5, 6), (4, 5, 6))
= (4, 5, 6), (7, 8)
nested_tup nested_tup
((4, 5, 6), (7, 8))
tuple([4, 0, 2]), tuple("string")
((4, 0, 2), ('s', 't', 'r', 'i', 'n', 'g'))
= ("pre", "post", 3)
tup 0], tup[-1] tup[
('pre', 3)
4, None, "foo") + (6, 0) + ("bar",), ("pre", "post") * 3 (
((4, None, 'foo', 6, 0, 'bar'), ('pre', 'post', 'pre', 'post', 'pre', 'post'))
Tuples are immutable, but they can contain mutable objects:
= (1, [2, 3])
t 1].append(4) # allowed: we mutate the list inside the tuple
t[ t
(1, [2, 3, 4])
What’s immutable is the container (which objects are stored), not necessarily the contents.
= (10, 20)
x, y x, y
(10, 20)
*b, c = (1, 2, 3, 4, 5)
a, a, b, c
(1, [2, 3, 4], 5)
range
is an immutable sequence of evenly spaced integers.range(start, stop, step)
start
→ first value (default = 0
)stop
→ sequence goes up to but not including this valuestep
→ increment (default = 1
)start
, stop
, and step
, and computes elements on demand.len()
, indexing, slicing, and membership testing.= range(10) # 0...9
r len(r), r[0], r[-1]
(10, 0, 9)
list(range(0, 20, 2))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
list(range(10, 0, -3))
[10, 7, 4, 1]
5 in range(10), 25 in range(10) # fast membership check
(True, False)
range(0, 10, 2)[2:5] # slicing a range yields another range
range(4, 10, 2)
dict
is likely the most important built-in Python data structure. A more common name for it is hash map or associative array. It is a flexibly sized collection of key-value pairs, where key and value are Python objects.
= {}
empty_dict = {'a' : 'some value', 'b' : [1, 2, 3, 4]}
d1 d1
{'a': 'some value', 'b': [1, 2, 3, 4]}
"b"] d1[
[1, 2, 3, 4]
"dept"] = "ISRT"
d1["b"] = list(range(3))
d1[ d1
{'a': 'some value', 'b': [0, 1, 2], 'dept': 'ISRT'}
"a" in d1, "z" in d1
(True, False)
d1["missing"]
would throw an error (KeyError
) if the key missing
doesn’t exist. d1.get("missing")
avoids that error and gives you a safe fallback (None
or the value you provide)."d") # [0, 1, 2] (key exists)
d1.get("age") # None (key missing)
d1.get("age", "N/A") # N/A (key missing, fallback given) d1.get(
'N/A'
"dummy"] = "temp"
d1[= d1.pop("dummy") # returns value and removes key
val val, d1
('temp', {'a': 'some value', 'b': [0, 1, 2], 'dept': 'ISRT'})
"x"] = 1
d1[del d1["x"] # delete by key (raises KeyError if absent)
d1
{'a': 'some value', 'b': [0, 1, 2], 'dept': 'ISRT'}
keys()
, values()
, items()
:list(d1.keys()), list(d1.values()), list(d1.items())
(['a', 'b', 'dept'],
['some value', [0, 1, 2], 'ISRT'],
[('a', 'some value'), ('b', [0, 1, 2]), ('dept', 'ISRT')])
= {"b": 999, "new": 1}
d2 # overwrites existing keys
d1.update(d2) d1
{'a': 'some value', 'b': 999, 'dept': 'ISRT', 'new': 1}
A set stores unique elements (unordered). Great for membership tests and set algebra.
set([2, 2, 2, 1, 3, 3]), {2, 2, 2, 1, 3, 3} # literal deduplicates too
({1, 2, 3}, {1, 2, 3})
= {1, 2, 3, 4, 5}
a = {3, 4, 5, 6, 7, 8}
b | b, a & b, a - b, a ^ b # union, intersection, difference, symmetric diff a
({1, 2, 3, 4, 5, 6, 7, 8}, {3, 4, 5}, {1, 2}, {1, 2, 6, 7, 8})
= {1, 2, 3}
s 4) # add single element
s.add(3, 5]) # add many
s.update([ s
{1, 2, 3, 4, 5}
3) # remove; raises KeyError if absent
s.remove(3) # remove; does nothing if absent
s.discard( s
{1, 2, 4, 5}
Function | Operator | Description |
---|---|---|
a.add(x) |
— | Add element x to a |
a.clear() |
— | Remove all elements |
a.remove(x) |
— | Remove x (error if absent) |
a.discard(x) |
— | Remove x (no error if absent) |
a.pop() |
— | Remove & return an arbitrary element |
a.union(b) |
a | b |
All elements in a or b |
a.update(b) |
a |= b |
In-place union |
a.intersection(b) |
a & b |
Elements in both |
a.intersection_update(b) |
a &= b |
In-place intersection |
a.difference(b) |
a - b |
Elements in a not in b |
a.difference_update(b) |
a -= b |
In-place difference |
a.symmetric_difference(b) |
a ^ b |
In a or b but not both |
a.symmetric_difference_update(b) |
a ^= b |
In-place symmetric diff |
a.issubset(b) |
a <= b |
All elems of a in b |
a.issuperset(b) |
a >= b |
All elems of b in a |
a.isdisjoint(b) |
— | No elements in common |
append
/extend
, remove
/discard
.In Python, different data types (list
, tuple
, range
, set
, dict
) support different sets of methods. To find out which ones are available and how to use them:
dir(type)
→ lists all attributes (including methods) of that type.dir(list) # attributes and methods of list
dir(tuple) # attributes and methods of tuple
append
, remove
, add
, keys
).__len__
, __add__
) are special methods, usually ignored in day-to-day use.help(type.method)
→ shows detailed documentation of a specific method.help(list.append) # details about append()
help(dict.update) # details about update()