Mar-20-2017, 11:28 AM
The unwritten rule is simple,never use range(len(sequence)).
If need index or manipulate index always
Eg:
Transforming Code into Beautiful, Idiomatic Python
Loop like a native: while, for, iterators, generators
If need index or manipulate index always
enumerate()
Eg:
# Find index of Lemon in list lst = ['Apple', 'Lemon', 'Orange'] for index, item in enumerate(lst): if item == 'Lemon': print(f'Lemon is at index: {index}')
Output:Lemon is at index: 1
We see this way in more places eg iterate over dict:emails = { 'Bob': '[email protected]', 'Alice': '[email protected]', } for name, email in emails.items(): print(f'{name} -> {email}')
Output:Bob -> [email protected]
Alice -> [email protected]
A couple of video:Transforming Code into Beautiful, Idiomatic Python
Loop like a native: while, for, iterators, generators