Example 1: python list comprehension
nums = [4, -7, 9, 1, -1, 8, -6]
half_of_nums = [x/2 for x in nums]
half_of_positive_nums = [x/2 for x in nums if x>=0]
Example 2: list comprehension python
vec = [-4, -2, 0, 2, 4]
doubled = [x*2 for x in vec]
greater_thatn_0 = [x for x in vec if x >= 0]
positive = [abs(x) for x in vec]
freshfruit = [' banana', ' loganberry ', 'passion fruit ']
fruits_nospaces = [weapon.strip() for weapon in freshfruit]
squares = [(x, x**2) for x in range(6)]
^
vec = [[1,2,3], [4,5,6], [7,8,9]]
unpacking_tuple = [num for elem in vec for num in elem]
Example 3: python list comprehension
a = [1,2,3,4,5]
b = [5,6,7,8,9]
print([i for i in a if i not in b])
Example 4: list comprehension
list_comp = [i+3 for i in range(20)]
for i in range(20):
print(i + 3)
Example 5: list comprehension python
numbers = [1,2,3]
new_list = []
for num in numbers:
new_list.append(num * 2)
print(new_list)
new_list_compre = [num * 2 for num in numbers]
print(new_list_compre)
double_list = [i*2 for i in range(1,5)]
print(double_list)
names = ['Alex', 'Beth', 'Caroline', 'Dave', 'Eleanor', 'Freddie']
short_names = [name for name in names if len(name) < 5]
print(short_names)
Example 6: simple list comprehension example
>>> squares = [i * i for i in range(10)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]