List Comprehension
List Comprehension offers a concise way to rearrange the values in a list or array.
The syntax is as follows:
newlist = [expression for item in iterable if condition == True]
Example
# Using a for loop
h_letters = []
for letter in 'human':
h_letters.append(letter)
print(h_letters)
# Using List Comprehension
h_letters = [ letter for letter in 'human' ]
print( h_letters)
Output
['h', 'u', 'm', 'a', 'n']
['h', 'u', 'm', 'a', 'n']
Example: Nested List
num_list = [y for y in range(100) if y % 2 == 0 if y % 5 == 0]
print(num_list)
Output
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]