Collections#
This is a cheatsheet of Python’s collection classes.
Summary Comparison#
Action |
List |
Tuple |
Set |
Dictionary |
---|---|---|---|---|
Create |
|
|
|
|
Add |
|
|
|
|
Contains |
|
|
|
|
Remove |
|
NA |
|
|
Get |
|
|
NA |
|
List#
Operation |
API |
---|---|
Create |
|
Add |
|
Remove |
|
Contains |
|
Get |
|
Set |
|
Size |
|
Insert |
|
Extend |
|
Remove all |
|
indexOf |
|
Sort |
|
Reverse |
|
Copy |
|
Tuple#
Operation |
API |
---|---|
Create |
|
Add |
|
Remove |
# cannot remove since tuples are immutable |
Contains |
|
Get |
|
Set |
NA # cannot set since tuples are immutable |
Size |
|
Insert |
# cannot insert since tuples are immutable |
Extend |
# + operator will concatenate which is extend |
Remove all |
|
indexOf |
|
Sort |
|
Reverse |
|
Copy |
|
Set#
Operation |
API |
---|---|
Create |
|
Add |
|
Remove |
|
Contains |
|
Size |
|
Remove All |
|
Union |
|
Intersection |
|
Difference |
|
Copy |
|
Get |
NA Can only determine if item is in set or not |
Set |
NA Cannot set the value of a specific element |
Insert |
NA Just add the object to the set. There is no order of elements. |
indexOf |
NA There is no order in a set |
Dictionary#
Operation |
API |
---|---|
Create |
|
Add |
|
Remove |
|
Contains |
|
Get |
|
Set |
|
Size |
|
Insert |
NA # dictionary order cannot change |
Extend |
|
Remove All |
|
indexOf |
# No easy way. Must iterate through values |
Sort |
# python retains original order of dictionary. recreate dictionary |
Reverse |
|
Copy |
|
Misc |
|
Simple Comprehensions#
# list comprehension
my_list = [ n for n in range(100) ]
# set comprehension
my_set = { n for n in range(100) }
# dictionary comprehensions & construction
my_dict = { key: value for key, value in zip(range(10), range(10, 20)) }
my_dict = dict( zip([k for k in range(10)], [v for v in range(10,20)]))
values = [ 6, 4, 2, 1, 3, 5]
my_dict = { key: values[key] for key in range(len(values)) }
my_dict = { key: value for key, value in enumerate(values) }
# There is NO tuple comprehension