Advanced Python Flashcards
What is a generator?
Specialized code that is able to return a series of values and to control the iteration process.
what is a iterator in python?
methods: __iter__() and __next__().
Key Concepts
Iterable: An object that can return an iterator. Examples include lists, tuples, dictionaries, and sets. These objects have an __iter__() method that returns an iterator.
Iterator: An object that represents a stream of data. It has a __next__() method that returns the next item from the collection. When there are no more items to return, it raises a StopIteration exception.
Define a custom iterator
class MyIterator:
def __init__(self, data):
self.data = data
self.index = 0
def \_\_iter\_\_(self): return self def \_\_next\_\_(self): if self.index < len(self.data): result = self.data[self.index] self.index += 1 return result else: raise StopIteration
Create an instance of MyIterator
my_iter = MyIterator([1, 2, 3])
Use the iterator
for item in my_iter:
print(item) # Output: 1 2 3
What is comprehension?
Comprehensions in Python provide a concise way to create sequences such as lists, dictionaries, and sets. They allow you to generate new sequences by applying an expression to each item in an existing sequence or iterable, optionally filtering elements with a conditional statement. Comprehensions are known for their readability and efficiency.
Types of Comprehensions:
List Comprehension
Dictionary Comprehension
Set Comprehension
Generator Comprehension
[expression for item in iterable if condition]
What are lambda Functions?
Lambda functions in Python are small, anonymous functions defined with the lambda keyword. They are often used for short, simple functions that are not reused elsewhere, providing a concise way to create function objects.
What is the syntax for a lambda function?
lambda arguments: expression
add = lambda x, y: x + y
print(add(3, 5)) # Output: 8
What are the 3 characteristics of lambda functions?
Anonymous: Lambda functions do not have a name, unlike regular functions defined using def.
Single Expression: They are limited to a single expression. The result of the expression is implicitly returned.
Inline Usage: Commonly used in places where a small function is required for a short period and is typically used inline.
What is a map function?
- Using Lambda with map()
The map() function applies a function to all items in an input list (or any iterable) and returns a map object (an iterator).
Give me an example of a map function
numbers = [1, 2, 3, 4]
squares = map(lambda x: x**2, numbers)
print(list(squares)) # Output: [1, 4, 9, 16]
What is a lambda filter function?
Using Lambda with filter()
The filter() function filters items out of an iterable based on a function that returns True or False.
Give an example of a lambda filter function
numbers = [1, 2, 3, 4, 5, 6]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens)) # Output: [2, 4, 6]
Explain using Lambda with sorted() or sort() with an example:
Lambda functions can be used to specify a key for sorting.
points = [(1, 2), (4, 1), (5, 3), (2, 4)]
sorted_points = sorted(points, key=lambda x: x[1])
print(sorted_points) # Output: [(4, 1), (1, 2), (5, 3), (2, 4)]
explain using Lambda with reduce()
The reduce() function from the functools module applies a function cumulatively to the items of an iterable.
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 24
What are closures in python?
A closure in Python refers to a function that retains access to the variables from its enclosing scope, even after the outer function has finished executing. Closures are a powerful feature used to create functions with extended lifetimes for their enclosing scopes’ variables.
Nested Functions: A closure involves at least two functions: an outer function and an inner function defined within it.
Enclosing Scope: The inner function captures variables from the outer (enclosing) function’s scope.
Lifetime Extension: The captured variables persist even after the outer function has finished executing.
Give an example of a python closure
Define the Outer Function:
The outer function has a local variable and an inner function.
def outer_function(x):
def inner_function(y):
return x + y
return inner_function
Return the Inner Function:
The outer function returns the inner function, which forms the closure.
add_five = outer_function(5)
Invoke the Closure:
The returned inner function retains access to x from the outer function.
print(add_five(3)) # Output: 8