Python Lists¶
Copying¶
Deep copying¶
Shallow copying¶
Flatten a list of lists¶
lazily get all the values
def from_iterable(iterables):
# chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
for it in iterables:
for element in it:
yield element
Deep copying¶
array.array
¶
- start off with
list
- use
array.array
if you run out of space- constrained to one type => less space
- thin wrapper on C arrays
- typically for interfacing C code
- still a dynamic
list
- same operations
array.array
vs np.array
¶
array.array
is way more lightweightnp
does a ton more stuff- numerical calc
Sets¶
frozenset
collections.Counter
>>> loot = {'sword': 1, 'bread': 3}
>>> inventory.update(loot)
>>> inventory
Counter({'bread': 3, 'sword': 1})
>>> more_loot = {'sword': 1, 'apple': 1}
>>> inventory.update(more_loot)
>>> inventory
Counter({'bread': 3, 'sword': 2, 'apple': 1})
Counter¶
from collections import Counter
votes = ["Person C", "Person A", "Person B", "Person A"] * 100
c = Counter(votes)
>>> c.most_common()
[('Person A', 200), ('Person C', 100), ('Person B', 100)]
for name, count in c.most_common():
percent = int(count * 100 / c.total())
print(f"{name}: {percent}%")
Last update:
2023-04-24