Monday, August 7, 2017

Transforming Code into Beautiful, Idiomatic Python

#Transforming Code in Beautiful, Idiomatic Python

# Example 1
#   - looping over a range of numbers

for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
    print(i**2)
    
#Better way 
for i in range(0, 10, 1):
    print(i**2)
    
    
# Example 2
#   - Looping over a collection
colors = ['red', 'green', 'blue', 'yellow']
for i in range(len(colors)):
    print(colors[i])

#Better way
for color in colors:
    print(color)
    
# looping backwards
colors = ['red', 'green', 'blue', 'yellow']
for i in range(len(colors)-1, -1, -1):
    print(colors[i])
    
#Better way
for color in reversed(colors):
    print(color)
    
# Example 3
#   - Looping over a collection and indicics
colors = ['red', 'green', 'blue', 'yellow']
for i in range(len(colors)):
    print(i, '==>', colors[i])
    
#Better way
for i, color in enumerate(colors):
    print(i, '==>', color) 
    
# Example 4
#   - Looping over two collections   
colors = ['red', 'green', 'blue', 'yellow']
months = ['jan', 'feb', 'mar', 'apr']

n = min(len(colors), len(months))
for i in range(0, n, 1):
    print(months[i], '==>', colors[i])
 
#Better way
for month, color in zip(months, colors):
    print(month, '==>', color)
    
# Example 5
#   - Looping sorted order
colors = ['red', 'green', 'blue', 'yellow']
for color in sorted(colors):
    print(color)

# sort in reverse way
for color in sorted(colors, reverse=True):
    print(color)

No comments:

Post a Comment