a comprehension helps to shorten the code
produces a list
does not only work for lists only, but for any iterable
new_output = [output expression for iterator in iterable]
my_list = ["ant", "bear", "cat", "dog", "eagle"]
my_new_list = []
for element in my_list:
if "a" in element:
my_new_list.append(element) #the output is a list with all elements with the substring "a"
my_list = ["ant", "bear", "cat", "dog", "eagle"]
my_new_list = [element for element in my_list if "a" in element]
my_list = ["ant", "bear", "cat", "dog", "eagle"]
my_new_list = ["a" in element for element in my_list] #this code creates only True and False in the list
[ … for … in … if … ]
[ action for itern in iteration if condition ]
print([num ** 2 for num in range(10) if num % 2 == 0 ])
#gives the square of even numbers, but no uneven numbers
[ … if … else … for … in … ]
[ action if condition else action for iter in iteration ]
print([num ** 2 if num % 2 == 0 else 0 for num in range(10)])
#gives the square of even numbers, otherwise 0
pairs = [(num1, num2) for num1 in rang(0,2) for num2 in rang(4,5)] #creates tuples of specific number pairs
print([[col for col in range(0,5)] for row in range(0,3)]) #creates a list matrix of 3x5 as [[0, 1, 2, 3, 4] , [0, 1, 2, 3, 4] , [0, 1, 2, 3, 4]]
my_nums = [1, 2, 3]
my_new_nums = [num + 1 for num in my_nums]
print([[col for col in range(0,5)] for row in range(0,5)]) #creates a list matrix of 5x5
produces a dictionary
print({num: num * (-1) for num in range(10)}) #creates a dictionary of numbers
cities = ['Hamburg', 'Berlin', 'Hannover', 'Stuttgart', 'Kiel', 'Ulm', 'Dresden']
print({city: len(city) for city in cities }) #creates a dictionary of cities and the number of letters in their name
produces a generator object
generator_object = (output expression for iterator in iterable)
generator expression will not need the memory and calculation resources of list comprehensions
generator functions do not return values, they yield values
my_gen_object = (num for num in range(0, 31)) #creates an object, not a list
print(list((num for num in range(0, 31)))) #outputs a list from the generator object
def num_sequence(n):
i = 0
while i < n:
i += 1
yield i
print(list(num_sequence(3))) #gives out the list 1, 2, 3.
def my_func(val):
for i in val:
yield i.upper() #makes upper case for all values in val