Generator

In Python, a generator is a special type of function that can be used to create iterable sequences of values on-the-fly. Unlike regular functions, which compute and return a value immediately, generators can generate a sequence of values over time, using the yield keyword. Example: The following fib function is a generator function that generates a sequence of Fibonacci numbers up to a given limit index n. def fib(n): a = [0, 1] i = 0 while i <= n: yield a[i%2] a[i%2] = a[0] + a[1] i += 1 The yield keyword is used to return each generated Fibonacci number as it is generated, which makes the function a generator....

April 7, 2023 · aaron

Comprehensions

In Python, there are several types of comprehensions that can be used to create new data structures from existing ones: list comprehension A list comprehension is a concise way to create a new list by iterating over an existing iterable and applying a transformation or filtering condition to each element. Here’s an example: my_list = [1, 2, 3, 4, 5] squared_list = [x*x for x in my_list] print(squared_list) # Output: [1, 4, 9, 16, 25] In this example, the list comprehension [x*x for x in my_list] creates a new list by squaring each element of my_list....

April 3, 2023 · aaron