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' (A)</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 (B)</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} (C)</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 (C)</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. (A)</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} (C)</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. (B)</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'] (C)</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. (D)</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 (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. (D)</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. (D)</p> Signup and view all the answers

Which part of the lambda expression is mandatory?

<p>The expression after the colon. (C), The keyword lambda. (D)</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. (D)</p> Signup and view all the answers

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

<p>It creates an additional reference to 'a'. (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. (A)</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. (A)</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. (B)</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. (C)</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. (D)</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. (A)</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. (C)</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] (B)</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])) (D)</p> Signup and view all the answers

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

<p>[4, 9, 16] (B)</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] (C)</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])) (D)</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. (A)</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)])) (B)</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')] (B)</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. (C)</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. (B)</p> Signup and view all the answers

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

<p>10 (D)</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. (A)</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. (B)</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. (B)</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. (A)</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. (A)</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. (A)</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. (D)</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. (A)</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. (C)</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. (B)</p> Signup and view all the answers

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

<p>lambda parameter: expression (C)</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') (B)</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. (A)</p> Signup and view all the answers

Flashcards

Reference Counting

A method used to track how many variables are referencing a particular object in memory.

Dynamic Typing

A programming language feature where variable types are not explicitly declared and are determined at runtime.

Static Typing

A programming language feature where variable types are declared and fixed at compile time, preventing type mismatches.

sys.getrefcount(a)

A Python function that returns the reference count of an object.

Signup and view all the flashcards

Type checking (Python)

Python figures out the type of an object when needed, not at compile time.

Signup and view all the flashcards

Memory Address (Example)

A unique location in computer memory to store a variable's data; often represented by a number/hexadecimal.

Signup and view all the flashcards

Variable in relation to an object

A variable in a dynamically typed language (like Python) is mainly a reference to an object in memory, not the object itself.

Signup and view all the flashcards

Type() Function in Python

A built-in Python function determining the type of an object pointed to by a variable

Signup and view all the flashcards

Dictionary Unpacking with **

The ** operator allows you to insert key-value pairs from one dictionary into another when creating a new dictionary.

Signup and view all the flashcards

Nested Unpacking with *

Python allows unpacking elements from nested lists or tuples by using multiple * operators.

Signup and view all the flashcards

Unpacking Strings

Strings can be unpacked just like lists or tuples, with each character being assigned to a separate variable.

Signup and view all the flashcards

Multiple * Usage

You can only use the * operator once directly in a unpacking assignment. However, you can use * within nested structures.

Signup and view all the flashcards

Extended Unpacking Benefits

Extended unpacking simplifies code, makes it more readable, and allows for flexible assignment of values.

Signup and view all the flashcards

Unpacking sets

Extracting individual elements from a set and assigning them to variables.

Signup and view all the flashcards

Unpacking with * operator

The * operator unpacks elements/Items of an iterable (a set, list, dictionary) into multiple variables.

Signup and view all the flashcards

Extended Unpacking

Using * and ** operators to unpack elements or key-value pairs from multiple iterables (sets, lists, and dictionaries).

Signup and view all the flashcards

Combining multiple dictionaries

Use ** operator to create a new dictionary with key-value pairs from multiple dictionaries.

Signup and view all the flashcards

** operator

Unpacks key-value pairs from a dictionary.

Signup and view all the flashcards

Set immutability

Sets do not maintain order; their elements are not stored in the order you add them.

Signup and view all the flashcards

Order in Sets

Sets do not preserve order. No guarantee on the order they will be accessed/iterated.

Signup and view all the flashcards

Unpacking with the * operator(Sets)

Unpacking set elements to different variables (order is not preserved)

Signup and view all the flashcards

Higher Order Functions

Functions that take other functions as arguments or return functions as their result.

Signup and view all the flashcards

Filter Function

Creates an iterator yielding those items of iterable for which function(item) is true.

Signup and view all the flashcards

Zip Function

Creates an iterator of tuples, aggregating elements from multiple iterables.

Signup and view all the flashcards

List Comprehension

A concise way to create lists by iterating over another iterable.

Signup and view all the flashcards

List Comprehension (map)

Using list comprehension to achieve the same result as the map function, applying a function to each element.

Signup and view all the flashcards

List Comprehension (filter)

Using list comprehension to achieve the same result as the filter function, filtering elements based on a condition.

Signup and view all the flashcards

Reducing Functions

Functions that combine an iterable recursively into a single value (also known as accumulators, aggregators, or folding functions).

Signup and view all the flashcards

Comprehension (map and filter)

List comprehension can be used to achieve the same result as combining map and filter functions.

Signup and view all the flashcards

Default Value Re-evaluation

In Python, default values for function parameters are evaluated only once when the function is defined, not every time it's called. This means if a default value is mutable (like a list or dictionary), changes made within the function persist across subsequent calls.

Signup and view all the flashcards

Mutable Default Value Issue

Using mutable objects (like lists or dictionaries) as default values in functions can lead to unexpected behavior. Changes made to the default value within the function persist across subsequent calls, potentially affecting other parts of the code.

Signup and view all the flashcards

Default Value Solution

To avoid mutable default value issues, set the default to None and test for it inside the function. If None, assign the current value. This ensures a fresh value is used each time the function is called.

Signup and view all the flashcards

Lambda Expression

An anonymous function that's defined inline using the 'lambda' keyword. It takes arguments and returns a value, defined in a single expression.

Signup and view all the flashcards

Lambda Syntax

A lambda expression has the form: lambda [parameter list]: expression. The parameter list can be empty or contain multiple parameters separated by commas. The expression is evaluated and returned when the lambda function is called.

Signup and view all the flashcards

Lambda Expression Example

A simple example would be lambda x: x * 2, which creates a function that multiplies its input by 2. You can then call this function like any other function.

Signup and view all the flashcards

Lambda Expression Use Cases

Lambda expressions are commonly used for simple operations, like sorting lists based on custom logic, or when passing functions as arguments to other functions.

Signup and view all the flashcards

Anonymous Function

A function that doesn't have a formal name, created using the lambda keyword. It's helpful for short, specific tasks that don't need a separate function definition.

Signup and view all the flashcards

Nested Functions

Functions defined inside other functions. The inner function can access variables from its enclosing function's scope.

Signup and view all the flashcards

Non local Scope

The scope of an enclosing function for nested functions. The inner function can access variables from this scope.

Signup and view all the flashcards

What happens if a variable is not found in a nested function's local scope?

Python searches the enclosing function's scope (non-local) first. If not found there, it looks in the global scope.

Signup and view all the flashcards

Enclosing Scope

The scope of the function that encloses a nested function. It's accessible from the nested function.

Signup and view all the flashcards

Global Scope

The outermost scope in a Python program. Variables defined here are accessible from anywhere.

Signup and view all the flashcards

Local Scope

The scope of a function. Variables defined inside a function are only accessible within its local scope.

Signup and view all the flashcards

Built-in Scope

The scope containing built-in Python functions and constants, accessible from any part of the program.

Signup and view all the flashcards

Name Resolution in Python

The process of finding the correct definition for a variable or function when using its name in code.

Signup and view all the flashcards

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