Looping through collections
Lists
Each:
for item in collection:
process(item)
Back to front:
for item in reversed(collection):
process(item)
With index
for index, item in enumerate(collection):
process(index, item)
Map (returns map object — ‘listify’ with list(mapObject)
):
map(lambda x: x * 2, numbers)
def process(number):
return number * 2
map(process, numbers)
Using list comprehensions as a kind of a map()
.
[x * 2 for x in [1, 2, 3, 4]]
Sets
Each key:
for key in {'height', 'weight'}:
process(key)
Dicts
Each key:
for key in {'height': 100, 'width': 200}:
process(key)
Each value:
for value in {'height': 100, 'width': 200}.values():
process(value)
Each key/value:
for key, value in {'height': 100, 'width': 200}.items():
process(key, value)
Strings
Each char:
for char in 'string':
process(char)