List Comprehensions in Python
- List comprehension methods are an elegant way to create and manage lists.
- List comprehensions are a more compact way of creating lists.
- More flexible than for loops, list comprehension is usually faster than other methods.
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.
-
First-Class Objects: In Python, functions are first-class objects. This means that functions can be passed around and used as arguments,
just like any other object (string, int, float, list, and so on). -
Inner Functions: define functions inside other functions. Such functions are called inner functions.
- Returning Functions From Functions: Python also allows you to use functions as return values.
-
Simple Decorators
decorators wrap a function, modifying its behavior
-
Syntactic Sugar: use decorators in a simpler way with the @ symbol
- Reusing Decorators: a decorator is just a regular Python function.
- Decorating Functions With Arguments
def do_twice(func): def wrapper_do_twice(*args, **kwargs): func(*args, **kwargs) func(*args, **kwargs) return wrapper_do_twice
- Returning Values From Decorated Functions: make sure the wrapper function returns the return value of the decorated function.
Fancy Decorators
- Decorating Classes: decor the whole class or decor the functions in class
- Nesting Decorators ```angular2html from decorators import debug, do_twice
@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}")
- Stateful Decorators
pure functions returning a value based on given arguments. Stateful decorators are quite the opposite, where the return value will depend on the current state, as well as the given arguments.