reading-notes

Software Development Reading Notes

View on GitHub

List Comprehensions in Python

Example 1:

# my_new_list = [ expression for item in list ]
digits = [x for x in range(10)]
print (digits)

output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Example 2:

# create a list with list comprehensions
multiples_of_three = [ x*3 for x in range(10) ]

print(multiples_of_three)
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

Example 3:

# use list comprehension to print the letters in a string
letters = [ letter for letter in "20,000 Leagues Under The Sea"]

print(letters)

output:

['2', '0', ',', '0', '0', '0', ' ', 'L', 'e', 'a', 'g', 'u', 'e', 's',
' ', 'U', 'n', 'd', 'e', 'r', ' ', 'T', 'h', 'e', ' ', 'S', 'e', 'a']

Primer on Python Decorators

Functions

a function returns a value based on the given arguments.

Fancy Decorators

@debug @do_twice def greet(name): print(f”Hello {name}”)

- Decorators With Arguments
```angular2html
@repeat(num_times=4)
def greet(name):
    print(f"Hello {name}")