reading-notes

Reading Notes

  1. What is the basic syntax of Python list comprehension, and how does it differ from using a for loop to create a list? Provide an example of a list comprehension that squares the elements in a given list of integers.
    • List comprehension is a powerful and concise method for creating lists in Python that becomes essential the more you work with lists, and lists of lists. It has the following syntax: my_new_list = [ expression for item in iterable_object ]
    • The literal iterable_object represents an iterable object such as a list, tuple, set, etc. We use the elements of the iterable_object to create a new list.
    • The term item represents an element of the iterable_object.
    • The expression represents the operation that we perform on the item. You can perform mathematical operations on item or pass it to a function.
    • my_new_list is the list created by executing expression on elements of iterable_object.
    • Example of a list comprehension that squares the elements in a given list of integers
      • myList=[1,2,3,4,5,6]
      • print(“The original list is:”,myList)
      • newList=[item**2 for item in myList]
      • print(“The output list is:”,newList)
  2. What is a decorator in Python?
    • a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.
  3. Explain the concept of decorators in Python. How do they work, and what are some common use cases for them? Provide an example of a simple decorator function from the reading.
    • In Python, decorators are a powerful feature that allows you to modify the behavior of functions or classes without changing their source code. Decorators work by wrapping a function or class with another function, which can add functionality before, after, or around the wrapped function. They provide a way to enhance or extend the behavior of existing functions or classes in a clean and reusable manner.

    • The basic syntax for using decorators in Python involves using the @ symbol followed by the name of the decorator function, placed just before the function or class definition. When the decorated function or class is called, it is actually the decorator function that gets invoked.

    • def say_hello(name): return f"Hello {name}"

    • def be_awesome(name): return f"Yo {name}, together we are the awesomest!"

    • def greet_bob(greeter_func): return greeter_func("Bob")