List Comprehensions is like one line for loop built inside of brackets. It allow us to build lists using a different notation.
Syntax:
my_list = [x for x in range(10)]
my_list = [expression for item in iterable if condition == True] # with if condition
Nested List Comprehensions
Syntax:
my_list = [expression for item in [expression for item in iterable]]
List Comprehensions Examples :
- Grab every letter in string :
my_list = [x for x in 'word'] print(my_list) # output : ['w', 'o', 'r', 'd']
- Grab every digit in a Number :
my_list = [x for x in str(123456)] print(my_list) # output : ['1', '2', '3', '4', '5', '6']
- Convert Celsius to Fahrenheit
celsius = [0,15,30,45.5] fahrenheit = [((9/5)*temp + 32) for temp in celsius ] print(fahrenheit)
- Nested List Comprehensions Example:
my_list = [ x**2 for x in [x**2 for x in range(11)]] print(my_list)