8.9. Idiom Patterns
Python
for
loop is equivalent toforEach
in other languagesOther languages
for
loop is Python'swhile
(sic!)
Code Complexity vs. Programmer Experience:
Time Complexity: https://wiki.python.org/moin/TimeComplexity
8.9.1. Foreach Element
Problem:
>>> data = ['a', 'b', 'c']
>>>
>>> i = 0
>>> while i < len(data):
... x = data[i]
... i += 1
... print(x)
a
b
c
Solution:
>>> data = ['a', 'b', 'c']
>>>
>>> for x in data:
... print(x)
a
b
c
8.9.2. Foreach Index
Problem:
>>> data = ['a', 'b', 'c']
>>>
>>> count = len(data)
>>> for i in range(count):
... x = data[i]
... print(x)
a
b
c
Solution:
>>> data = ['a', 'b', 'c']
>>>
>>> for x in data:
... print(x)
a
b
c
8.9.3. Range
Do something multiple times
Problem:
>>> i = 0
>>> while i < 3:
... print('hello')
... i += 1
hello
hello
hello
Solution:
>>> for _ in range(3):
... print('hello')
hello
hello
hello
8.9.4. Sum
Problem:
>>> data = [1, 2, 3]
>>>
>>> result = 0
>>> for value in data:
... result += value
Solution:
>>> data = [1, 2, 3]
>>>
>>> result = sum(data)
8.9.5. Enumerate
Problem:
>>> data = ['a', 'b', 'c']
>>>
>>> index = 0
>>> for value in data:
... print(index, value)
... index += 1
0 a
1 b
2 c
Solution:
>>> data = ['a', 'b', 'c']
>>>
>>> for index, value in enumerate(data):
... print(index, value)
0 a
1 b
2 c
8.9.6. Zip
Problem:
>>> data1 = ['a', 'b', 'c']
>>> data2 = [1, 2, 3]
>>>
>>> count = min(len(data1), len(data2))
>>> result = []
>>> for i in range(count):
... a = data1[i]
... b = data2[i]
... result.append((a, b))
Solution:
>>> data1 = ['a', 'b', 'c']
>>> data2 = [1, 2, 3]
>>>
>>> result = zip(data1, data2)
8.9.7. Any
Problem:
>>> users = [
... {'firstname': 'Mark', 'lastname': 'Watney', 'age':40},
... {'firstname': 'Melissa', 'lastname': 'Lewis', 'age':41},
... {'firstname': 'Rick', 'lastname': 'Martinez', 'age':39},
... {'firstname': 'Alex', 'lastname': 'Vogel', 'age':15},
... ]
>>>
>>> result = True
>>> for user in users:
... if not user['age']>=18:
... result = False
>>>
>>> if result:
... print('All users are adult')
... else:
... print('We have at least one child')
We have at least one child
Solution:
>>> users = [
... {'firstname': 'Mark', 'lastname': 'Watney', 'age':40},
... {'firstname': 'Melissa', 'lastname': 'Lewis', 'age':41},
... {'firstname': 'Rick', 'lastname': 'Martinez', 'age':39},
... {'firstname': 'Alex', 'lastname': 'Vogel', 'age':15},
... ]
>>>
>>> if all(user['age']>=18 for user in users):
... print('All users are adult')
... else:
... print('We have at least one child')
We have at least one child
8.9.8. List Comprehension
Problem:
>>> data = ['a', 'b', 'c']
>>>
>>> result = []
>>> for x in data:
... result.append(x)
Solution:
>>> data = ['a', 'b', 'c']
>>>
>>> result = [x for x in data]
8.9.9. Set Comprehension
Problem:
>>> data = ['a', 'b', 'c']
>>>
>>> result = set()
>>> for x in data:
... result.add(x)
Solution:
>>> data = ['a', 'b', 'c']
>>>
>>> result = {x for x in data}
8.9.10. Dict Comprehension
Problem:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>>
>>> result = {}
>>> for key, value in data.items():
... result[key] = value
Solution:
>>> data = {'a': 1, 'b': 2, 'c': 3}
>>>
>>> result = {k:v for k,v in data.items()}
8.9.11. For Else
x in data
Problem:
>>> data = [1, 2, 3]
>>> x = 10
>>>
>>> found = False
>>> for value in data:
... if value == x:
... print('Found')
... found = True
... break
>>> if not found:
... print('Not Found')
Not Found
Solution:
>>> data = [1, 2, 3]
>>> x = 10
>>>
>>> for value in data:
... if value == x:
... print('Found')
... break
... else:
... print('Not Found')
Not Found
8.9.12. While Else
x in data
Problem:
>>> data = [1, 2, 3]
>>> x = 10
>>>
>>> found = False
>>> while i < len(data):
... value = data[i]
... i += 1
... if value == x:
... print('Found')
... found = True
... break
>>> if not found:
... print('Not Found')
Not Found
Solution:
>>> data = [1, 2, 3]
>>> x = 10
>>>
>>> while i < len(data):
... value = data[i]
... i += 1
... if value == x:
... print('Found')
... break
... else:
... print('Not Found')
Not Found
8.9.13. Str Startswith One
Problem:
>>> data = 'mwatney@nasa.gov'
>>>
>>> data[:7] == 'mwatney'
True
Solution:
>>> data = 'mwatney@nasa.gov'
>>>
>>> data.startswith('mwatney')
True
8.9.14. Str Startswith Many
Problem:
>>> data = 'mwatney@nasa.gov'
>>>
>>> data[:7] == 'mwatney' or data[:6] == 'mlewis'
True
Solution:
>>> data = 'mwatney@nasa.gov'
>>>
>>> data.startswith(('mwatney', 'mlewis'))
True
8.9.15. Str Endswith One
Problem:
>>> data = 'mwatney@nasa.gov'
>>>
>>> data[-8:] == 'nasa.gov'
True
Solution:
>>> data = 'mwatney@nasa.gov'
>>>
>>> data.endswith('nasa.gov')
True
8.9.16. Str Endswith Many
Problem:
>>> data = 'mwatney@nasa.gov'
>>>
>>> data[-8:] == 'nasa.gov' or data[-7:] == 'esa.int'
True
Solution:
>>> data = 'mwatney@nasa.gov'
>>>
>>> data.endswith(('nasa.gov', 'esa.int'))
True
8.9.17. Join Strings with Character
Problem:
>>> data = ['Mark', 'Melissa', 'Rick']
>>>
>>> result = ''
>>> for user in data:
... result += user + ','
>>> result = result.removesuffix(',')
Solution:
>>> data = ['Mark', 'Melissa', 'Rick']
>>>
>>> result = ','.join(data)
8.9.18. Join Lines with Newlines
Problem:
>>> data = ['line1', 'line2', 'line3']
>>>
>>> result = [line+'\n' for line in data]
Solution:
>>> data = ['line1', 'line2', 'line3']
>>>
>>> result = '\n'.join(data) + '\n'
8.9.19. Map
Problem:
>>> def transform(x):
... return ...
...
>>> data = [1, 2, 3]
>>>
>>> result = [transform(x) for x in data]
Solution:
>>> def transform(x):
... return ...
...
>>> data = [1, 2, 3]
>>>
>>> result = map(transform, data)
8.9.20. Filter
Problem:
>>> def predicate(x):
... return ...
...
>>> data = [1, 2, 3]
>>>
>>> result = [x for x in data if predicate(x)]
Solution:
>>> def predicate(x):
... return ...
...
>>> data = [1, 2, 3]
>>>
>>> result = filter(predicate, data)
8.9.21. Other Programming Languages
For:
for (int i = 0; i <= 10; i++) # C/C++/Java for (var i = 0; i <= 10; i++) # JavaScript i = 0 while i <= 10: # Python i += 1
ForEach Index:
for (let idx in collection) # JavaScript for idx in range(len(collection)) # Python
ForEach Element:
for (var element : collection) # Java for (let element of collection) # JavaScript for element in collection # Python for i in range(0,10) # Python
Enumerate:
for (int i = 0; i <= collection.length; i++) # C++ / JAVA / JavaScript element = collection[i] for (let i in collection) # JavaScript element = collection[i] for i in range(len(collection)): # Python (1to1 algorithm conversion) element = collection[i] for i, element in enumerate(collection) # Python (Pythonic way)
Zip:
for (int i = 0; i <= collection.length; i++) # C++ / JAVA / JavaScript a = collection1[i] b = collection2[i] for i in range(len(collection1)): # Python (1to1 algorithm conversion) a = collection1[i] b = collection2[i] for a, b in zip(collection1, collection2) # Python (Pythonic way)