Basically Python list comprehensions powerful and essential method to use, they are used to make your code more readable and eaiser to understand.
my_new_list = [ expression for item in list ]
digits = [x for x in range(10)]
output of printing digits –> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
squares = [x**2 for x in range(10)]
even_numbers = [ x for x in range(1,20) if x % 2 == 0]
letters = [name[0] for name in authors]
letters = [ letter for letter in "20,000 Leagues Under The Sea"]
output –> ['2', '0', ',', '0', '0', '0', ' ', 'L', 'e', 'a', 'g', 'u', 'e', 's', ' ', 'U', 'n', 'd', 'e', 'r', ' ', 'T', 'h', 'e', ' ', 'S', 'e', 'a']
lower_case = [ letter.lower() for letter in ['A','B','C'] ]
upper_case = [ letter.upper() for letter in ['a','b','c'] ]
user_data = "Elvis Presley 987-654-3210"
phone_number = [ x for x in user_data if x.isdigit()]
output –> list in which each element represents a number from the string above.
Using list comprehension, we can iterate through the lines of text in the file and store their contents in a new list.
file = open("dreams.txt", 'r')
poem = [ line for line in file ]
for line in poem:
print(line)
output –> Hold fast to dreams
For if dreams die
Life is a broken-winged bird
That cannot fly.
-Langston Hughs
nums = [double(x) for x in range(1,10)] print(nums)
- we can add a condition to the previous for doubling only even numbers:
even_nums = [double(x) for x in range(1,10) if x%2 == 0]
- Additional arguments can be added to create more complex logic:
nums = [x+y for x in [1,2,3] for y in [10,20,30]]
```
output –> [11, 21, 31, 12, 22, 32, 13, 23, 33]
Decorators provide a simple syntax for calling higher-order functions.
First-Class Objects functions are first-class objects. This means that functions can be passed around and used as arguments
Inner Functions they are functions inside other functions, the inner functions are not defined until the parent function is called, the printing only happens when the inner functions are executed.