Python Unpacking and Merging Dictionaries
49 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What will be the result of the expression {**d1, 'a': 10, 'c': 3} if d1 is defined as {'a': 1, 'b': 2}?

  • {'a': 1, 'c': 3, 'b': 2}
  • {'a': 10, 'b': 2, 'c': 3} (correct)
  • {'a': 1, 'b': 2}
  • {'a': 10, 'c': 3}
  • In a nested unpacking assignment, how many times can the * operator be used in the left-hand side?

  • Only once (correct)
  • Not at all
  • At least twice
  • As many as desired
  • Given the list li = [1, 2, [3, 4]], what will the variable b hold after unpacking a, b, c = li?

  • 3
  • 2 (correct)
  • [3, 4]
  • None of the above
  • What is the result of the unpacking a, *b, (c, d, e) = [1, 2, 3, 'XYZ']?

    <p>a=1, b=[2, 3], c='X', d='Y', e='Z'</p> Signup and view all the answers

    What happens if you try to use the * operator more than once in a single unpacking assignment?

    <p>It will result in a syntax error</p> Signup and view all the answers

    What will be the output of print(s) if s is defined as s = {7, -77, 6, 'g'}?

    <p>{-77, 'g', 6, 7}</p> Signup and view all the answers

    Which assignment will result in a = -77, b = ['g', 6'], and c = 7 from s?

    <p>a, *b, c = s</p> Signup and view all the answers

    What does the expression s = {*d1, *d2, *d3} produce when d1, d2, and d3 contain overlapping keys?

    <p>A set including all unique keys.</p> Signup and view all the answers

    What is the result of d = {**d1, **d2, **d3} if d1, d2, and d3 all contain the key 'h'?

    <p>{'p': 1, 'y': 2, 't': 3, 'h': 5, 'o': 6, 'n': 7}</p> Signup and view all the answers

    Which statement about unpacking sets is true?

    <p>The * operator can be used with sets but doesn't guarantee order.</p> Signup and view all the answers

    What will be the output of print(li) if li = [*d1, *d2, *d3]?

    <p>['p', 'y', 't', 'h', 'h', 'o', 'n']</p> Signup and view all the answers

    What is not a valid use of the ** operator?

    <p>Using it on the left side of an assignment.</p> Signup and view all the answers

    Which of the following would result in extracting only the first key from a dictionary?

    <p>a, *b = d</p> Signup and view all the answers

    What will happen if the function log is called without providing a value for the parameter dt?

    <p>It will set <code>dt</code> to the current date/time.</p> Signup and view all the answers

    Which statement regarding default values in function arguments is correct?

    <p>Using mutable objects as default values can lead to unexpected behavior.</p> Signup and view all the answers

    Which part of the lambda expression is mandatory?

    <p>The expression after the colon.</p> Signup and view all the answers

    What is a primary advantage of using lambda expressions?

    <p>They allow for concise and anonymous function creation.</p> Signup and view all the answers

    What happens when 'a' is passed to sys.getrefcount()?

    <p>It creates an additional reference to 'a'.</p> Signup and view all the answers

    In statically typed languages like C++ and Java, what will occur if you try to assign a different type to a variable?

    <p>This operation will cause a type error.</p> Signup and view all the answers

    How does Python treat variables in terms of typing?

    <p>Python variables can change the type of object they reference dynamically.</p> Signup and view all the answers

    What does the type() function do when called on a variable in Python?

    <p>It returns the type of the object currently referenced by that variable.</p> Signup and view all the answers

    If 'my_str' is initially assigned the string 'MEK3100', what will happen when it is later assigned the value 10?

    <p>It will remove the reference to the original string.</p> Signup and view all the answers

    In the example given, what does the memory address 0x1000 represent?

    <p>The value of the integer 10.</p> Signup and view all the answers

    What is true about the variable 'my_str' in Python?

    <p>It can point to objects of different types at different times.</p> Signup and view all the answers

    What does the reference count indicate about an object in memory?

    <p>The number of variables pointing to the memory address of that object.</p> Signup and view all the answers

    What will be the output of list(filter(None, [0, 1, 2, 3, 4]))?

    <p>[1, 2, 3, 4]</p> Signup and view all the answers

    Which of the following correctly demonstrates using zip with three iterables?

    <p>list(zip([1, 2, 3], [10, 20, 30], [40, 50, 60]))</p> Signup and view all the answers

    What does the expression [x**2 for x in [2, 3, 4]] return?

    <p>[4, 9, 16]</p> Signup and view all the answers

    What is the output of list(map(lambda x, y: x + y, [1, 2, 3], [10, 20, 30]))?

    <p>[11, 22, 33]</p> Signup and view all the answers

    Which of the following expressions effectively filters out odd numbers from the list [1, 2, 3, 4]?

    <p>list(filter(lambda n: n % 2 == 0, [1, 2, 3, 4]))</p> Signup and view all the answers

    What is the purpose of reducing functions in Python?

    <p>To combine elements of an iterable into a single cumulative value.</p> Signup and view all the answers

    Which expression correctly combines map and filter to square numbers less than 25 from the range of 10?

    <p>list(filter(lambda x: x &lt; 25, [x**2 for x in range(10)]))</p> Signup and view all the answers

    What will the output be for list(zip(range(100), 'abcd'))?

    <p>[(0,'a'), (1,'b'), (2,'c')]</p> Signup and view all the answers

    What is meant by 'nonlocal scope' in the context of nested functions?

    <p>The scope that is neither global nor local to the inner function.</p> Signup and view all the answers

    Which statement is true when referring to a variable from an enclosing scope within an inner function?

    <p>The inner function first checks its own local scope for the variable.</p> Signup and view all the answers

    What will the output be when calling the function 'outer_func' defined in the example?

    <p>10</p> Signup and view all the answers

    In which situation will Python look for a variable in the global scope when executing an inner function?

    <p>When the variable is not defined in the inner function's local or enclosing scope.</p> Signup and view all the answers

    What happens if the inner function tries to print a variable that is only defined locally in the outer function?

    <p>It will raise an undefined variable error.</p> Signup and view all the answers

    What would happen if an inner function attempts to modify a variable defined in the outer function without declaring it as 'nonlocal'?

    <p>The inner function will create a new local variable.</p> Signup and view all the answers

    Which of the following correctly describes the scopes accessed by an inner function?

    <p>Global, built-in, enclosing, and local scopes.</p> Signup and view all the answers

    If 'outer_func' contains a variable 'a' defined as 10, what will be the value of 'a' inside its inner function after calling 'outer_func'?

    <p>10, since it is in the enclosing scope.</p> Signup and view all the answers

    What is the main issue with using a mutable object or callable as a default argument in a function?

    <p>It could lead to unexpected behavior if modified outside the function.</p> Signup and view all the answers

    What happens when you provide a specific value for the parameter dt in the log function?

    <p>The specific date/time passed will be used instead of the current date/time.</p> Signup and view all the answers

    Which of the following best describes a lambda expression?

    <p>An inline function that is defined without a formal name or return statement.</p> Signup and view all the answers

    In the log function implementation, what is the purpose of checking if dt is None?

    <p>To set <code>dt</code> to the current date/time only if no specific value is given.</p> Signup and view all the answers

    When defining a function with default arguments, what happens if the default argument is mutable?

    <p>Changes made to the mutable object will affect future calls to the function.</p> Signup and view all the answers

    What is the correct syntax for creating a lambda function with one parameter?

    <p>lambda parameter: expression</p> Signup and view all the answers

    Which scenario would correctly utilize the log function to log a message with custom date/time?

    <p>log('Event happened', dt='2024-09-14 12:00:00')</p> Signup and view all the answers

    Why should default values for function parameters not be evaluated when the function is defined?

    <p>To allow for dynamic values that reflect the state at the time of the call.</p> Signup and view all the answers

    Study Notes

    Programming 2 - Lecture 1

    • Python is an Object-Oriented Programming (OOP) language.
    • Almost everything in Python is an object.
    • Data objects have properties and methods.
    • A class is like an object constructor, or a blueprint for creating objects.

    Object Oriented Programming

    • Python supports many data types, including integers, floats, strings, lists, sets, dictionaries, and more.
    • Each data type is an object.
    • Each object has a type, an internal representation, and associated methods.
    • An object is an instance of a type (e.g., 777 is an instance of int, "Python" is an instance of str).

    Object Oriented Programming

    • Creating a class uses the keyword class.
    • Creating objects from a class uses the class name followed by parentheses.
    • Example (using MyClass class) class MyClass: x = 5 p1 = MyClass() print(p1.x)

    The __init__ Function

    • All classes have an __init__ function, automatically called when an object is created.
    • Used to initialize properties of an object to meaningful values.

    Object Methods

    • Objects can have methods (functions associated with an object).
    • The parameter self refers to the object itself.

    Modify Object Properties

    • Object properties can be modified after they're created.

    Defining Your Own Print Method

    • User can define methods for handling the output of objects using __str__ method.
    • Custom print methods change how objects are printed

    Other Special Methods

    • Python has special methods for operators like +, -, <, >, len(), str().

    add Method

    • Used for custom operator handling within a class, for example adding two coordinate objects

    Public vs Private Members

    • Python does not have private variables in the strict sense.
    • Single underscore prefix is a convention for protected attributes.
    • Double underscore prefix is a convention for private attributes, but does not enforce privacy.

    Lecture 2 - Inheritance

    • Inheritance defines a way for a new class to inherit properties and methods from an existing class.
    • Parent class (base class) is the class being inherited from.
    • Child class (derived class) inherits from the parent class.

    Lecture 3 - Variables & Memory

    • Variables are memory references that point to objects.
    • The id() method returns the memory address of an object.
    • The hex() method converts a base-10 integer to a hexadecimal string.
    • Reference counting counts how many variables refer to an object.
    • Mutability refers to whether the internal state of an object can be changed (immutable).
    • Immutable objects (integers, booleans) do not change.
    • Mutable objects (lists) can change.

    Lecture 4 - Functions Parameters

    • Arguments are the values passed to a function when it's called.
    • Parameters are the variables inside a function's definition.
    • Positional arguments are passed in the order they are declared.
    • Keyword arguments are passed using the parameter names.
    • Default values for parameters can be specified in the function definition; using def func(a, b=0)
    • Default values are evaluated at the time of function definition (not every time it's called).

    Lecture 5 - First-Class Functions

    • Lambda expressions are anonymous functions.
    • They're defined with the lambda keyword, and their body is a single expression.
    • Lambdas can be assigned to variables and passed as arguments to functions (like other functions defined with def).

    Lecture 6 - Scopes & Closures

    • A variable's scope is the part of the program where the variable is visible and accessible.
    • There are three scopes
      • Built-in scope
      • Global scope
      • Local scope (function local scope)
    • Python searches scopes locally, then globally, then if not found, the built-in scope.
    • If an inner function uses variables from the outer function scopes for its calculations and operations, then the inner function will become a closure in Python.

    Lecture 7 - Decorators

    • Decorators are functions that wrap another function and add functionality to it
    • Decorators can be useful for adding functionality.
    • Decorators are often used for tasks like logging, timing and other things like validation.

    Lecture 8 - Tuples as Data Structures

    • Tuples are sequences.
    • Tuples contain heterogeneous data.
    • Tuples are immutable.
    • Tuples are more useful when the order of the objects matter.
    • Named tuples extend tuples by giving names to entries.

    Lecture 9 - Sequence Types

    • Sequences can be indexed, sliced and iterated over

    Lecture 10 - Iterables & Iterators

    • Iterables are objects that can be iterated over.
    • Iterators are objects that implement the iter and next methods.
    • The iter method returns a new iterator object each time from the iterable.

    Lecture 11 - Generators

    • Python's yield keyword creates a generator, instead of returning the whole list.
    • Generators are also iterators and can handle infinite sequences.
    • Python's iter and next methods are what makes for/while loops work in the first place.

    Studying That Suits You

    Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

    Quiz Team

    Related Documents

    Description

    This quiz tests your understanding of dictionary unpacking and assignment in Python, including nested unpacking and the use of the * and ** operators. It covers various scenarios and expected outcomes to ensure a comprehensive grasp of these concepts.

    More Like This

    Benefits of Using a Dictionary
    6 questions
    Dictionary Words A-I Quiz
    10 questions
    Using a Dictionary and Etymology
    5 questions
    Use Quizgecko on...
    Browser
    Browser