Python for Data Analysis
- 131Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is computer programming?
131 questions
- 1
What is computer programming?
Model answer
Computer programming is the process of giving a computer instructions to perform an action or set of actions.
Explanation
A program supplies instructions to a computer; programming languages provide ways to write those instructions.
- 2
How are binary numbers related to the way computer hardware operates?
Model answer
Computers operate using binary, represented by ones and zeros, which correspond to sequences of on and off transistor states.
Explanation
Programs ultimately control computer hardware, whose transistors have on and off states represented as binary digits.
- 3
Contrast low-level and high-level programming languages.
Model answer
Low-level languages are harder to use and often machine-specific, while high-level languages use more human-friendly syntax and simpler structures.
Explanation
Early languages were difficult to use and often designed for specific machines; higher-level languages use more human-friendly syntax.
- 4
What characteristics have made Python popular among data professionals?
Model answer
Python is a versatile, powerful, high-level language that is relatively easy to learn and use.
Explanation
Python is described as versatile, approachable, and powerful, with a large ecosystem of reusable libraries and tools.
- 5
How do open-source development and libraries contribute to Python's usefulness?
Model answer
Python is open source, and developers have created many reusable libraries and tools that make common and specialized tasks easier.
Explanation
Open-source development has supported a large collection of libraries for tasks ranging from basic calculations to machine learning.
- 6
What is a programming library, and why might a data professional use one?
Model answer
A library is a reusable collection of code that can save time by providing functions and tools for common tasks.
Explanation
A library is reusable code; using an existing sum function, for instance, avoids writing a new addition function for each use case.
- 7
Name several kinds of tasks Python can perform, based on the examples in the content.
Model answer
Python can output text, perform calculations, assign and use variables, evaluate comparisons, run conditional logic and loops, and call functions.
Explanation
A single Python statement can print text, calculate values, assign variables, compare values, or invoke reusable code.
- 8
How do the uses of one equals sign and two equals signs differ in Python?
Model answer
Use two equals signs to compare values for equality and one equals sign to assign a value to a variable.
Explanation
Python uses two equals signs to test equivalence; a single equals sign assigns a value to a variable.
- 9
What is Jupyter Notebook, and what kinds of content can it combine?
Model answer
Jupyter Notebook is an open-source web application for creating and sharing documents that combine live code, text, formulas, and visualizations.
Explanation
A notebook contains modular cells and can combine live code with output, text, formulas, and visualizations in one shareable document.
- 10
How does a notebook's cell-based structure support data analysis compared with a linear terminal-based editor?
Model answer
Notebook cells organize code into editable sections, while Markdown adds formatted text and explanations; code, results, and visualizations can be kept together.
Explanation
Cells can be rearranged or edited, and Markdown can add formatted explanations; this supports analysis and presentation in one document.
- 11
What is the central idea of object-oriented programming?
Model answer
Object-oriented programming organizes data and the code that manipulates it within objects, making code more organized, accessible, and reusable.
Explanation
Object-oriented programming organizes data and code that manipulates it into objects, supporting organization and reuse.
- 12
Explain the relationships among a class, an object, a method, and an attribute.
Model answer
A class defines a data type and bundles data with functionality; an object is an instance of that class, with associated methods and attributes.
Explanation
An object is an instance of a class. A class bundles data and functionality; methods are functions associated with a class, while attributes describe an object or class.
- 13
How does Python dot notation access methods and attributes, and how can you distinguish the two?
Model answer
Dot notation accesses an object's methods and attributes. Methods use parentheses, while attributes do not.
Explanation
A dot connects an object to its method or attribute; methods are called with parentheses, while attributes are accessed without them.
- 14
What can attributes such as a DataFrame's shape and columns tell you?
Model answer
The shape and columns attributes describe a DataFrame's dimensions and column names; accessing them does not change the DataFrame.
Explanation
DataFrame shape reports dimensions, while columns returns an index of column names; these attributes describe the object rather than modifying it.
- 15
What does a Python variable refer to, and where is its value stored?
Model answer
A variable is a named reference to a value stored in computer memory, rather than the value itself.
Explanation
Variables are names that point to values stored in memory. Meaningful names make the data easier to identify and work with.
- 16
What is a data type? Give several examples of Python data types.
Model answer
A data type describes a piece of data and the kinds of values or operations associated with it; Python examples include strings, integers, floats, lists, and dictionaries.
Explanation
A data type describes data according to its values, programming-language representation, or supported operations; examples include strings, integers, floats, lists, and dictionaries.
- 17
What three questions are useful to answer before creating a variable?
Model answer
Before creating a variable, consider its name, data type, and starting value.
Explanation
Naming the variable, identifying its type, and choosing its starting value help keep the variable meaningful and usable.
- 18
What is dynamic typing in Python?
Model answer
Dynamic typing means Python determines the type from the assigned object, and a variable can refer to objects of different types over time.
Explanation
Python infers a variable's type from its assigned object, and a variable can later refer to objects of different data types.
- 19
Why should a variable be initialized before it is used?
Model answer
A variable generally needs to be initialized with a value before it can be used; Python does not provide most new variables with a default value.
Explanation
Most variables have no default value, so they must be assigned or initialized before they are used.
- 20
Distinguish assignment from an expression.
Model answer
Assignment stores a value in a variable, while an expression combines values, symbols, or variables to produce a result.
Explanation
Assignment stores a value in a variable; an expression combines values, symbols, or variables to produce a result when evaluated.
- 21
Why does calling a conversion function alone not necessarily change a variable's stored value?
Model answer
To change a variable's stored value through conversion, assign the converted result back to the variable.
Explanation
Calling str on a value produces a string, but the variable retains its original value unless the converted result is assigned back to it.
- 22
Define strings, integers, and floats, including the mutability of strings.
Model answer
A string is an immutable sequence of characters, an integer represents a whole number without a fraction, and a float represents a number with a decimal component.
Explanation
Strings are character sequences and are immutable; integers are whole numbers without fractions; floats represent numbers with decimal components.
- 23
What is Boolean data, and how do comparisons produce it?
Model answer
Boolean data has two possible values, usually True or False, and comparison expressions produce Boolean results.
Explanation
A Boolean has two possible values, usually True and False; comparisons produce Boolean results used to control program logic.
- 24
How can you check the data type of a Python value?
Model answer
Use the type function to identify an object's data type, such as str, int, or float.
Explanation
The type function reports a value's class, such as str, int, or float, helping identify which data type is being handled.
- 25
Compare implicit and explicit type conversion in Python.
Model answer
Implicit conversion happens automatically, while explicit conversion uses functions such as int, float, or str to request a type change.
Explanation
Implicit conversion occurs automatically, such as converting an integer to a float in mixed arithmetic; explicit conversion is requested by the programmer using functions such as int, float, or str.
- 26
Why can combining an integer and a string cause a TypeError, and how can you address it?
Model answer
Incompatible data types can cause a TypeError when combined; convert the values to compatible types before performing the operation.
Explanation
Mixing incompatible types, such as adding an integer and a string, can cause a TypeError; converting values to compatible types can avoid this.
- 27
How can reassignment and notebook cell order affect a variable's value?
Model answer
Reassignment changes a variable's current value, and notebook cell execution order matters because rerunning an earlier assignment can overwrite a later one.
Explanation
A reassignment changes the value a variable refers to; rerunning an earlier notebook cell can overwrite a later assignment and change the variable's current value.
- 28
Why are descriptive variable names useful?
Model answer
Meaningful variable names help the programmer and collaborators understand what data a variable stores.
Explanation
Variable names serve as reminders about stored data; names such as age_list communicate more than generic names such as x.
- 29
Which kinds of names should you avoid using for variables, and why?
Model answer
Avoid reserved keywords and existing function names when naming variables, because keywords cannot be reassigned as variable names and function names can be overwritten.
Explanation
Python keywords such as for, in, if, and else have reserved purposes and cannot be used as variable names; names of existing functions should also be avoided.
- 30
State the main Python variable-naming restrictions described in the content.
Model answer
A variable name may contain letters, numbers, and underscores, must start with a letter or underscore, and cannot include spaces, special characters, or parentheses.
Explanation
Variable names can contain letters, numbers, and underscores, must begin with a letter or underscore, and cannot contain spaces, special characters, or parentheses.
- 31
What does it mean that Python is case-sensitive?
Model answer
Python is case-sensitive, so capitalization differences matter in variable names.
Explanation
Python distinguishes capitalization, so differently capitalized names are not treated as identical variable names.
- 32
How do parentheses affect the order in which Python evaluates arithmetic expressions?
Model answer
Python evaluates parenthesized calculations first and otherwise follows the standard mathematical order of operations.
Explanation
Parenthesized expressions are evaluated first; without parentheses, Python uses standard mathematical order of operations.
- 33
What is a function, and how is print used in Python 3?
Model answer
A function is reusable code for a specific task; in Python 3, print is called with parentheses.
Explanation
A function is a reusable body of code. In Python 3, print is a function and uses parentheses, even when no arguments are supplied.
- 34
Describe the basic structure of a Python function definition.
Model answer
Define a function with def, followed by its name and parameters in parentheses, a colon, and an indented body.
Explanation
The def keyword begins a function definition; the function name and parameters follow in parentheses, then a colon introduces an indented body.
- 35
Distinguish a function parameter from an argument.
Model answer
Parameters are the inputs named in the function definition; arguments are the actual values provided in a function call.
Explanation
Parameters are names in a function definition; arguments are the values supplied when the function is called.
- 36
What role does indentation play in Python code blocks?
Model answer
Indentation defines which code belongs to a block; consistent indentation is required, and four spaces is a common readable convention.
Explanation
Python uses indentation to show which lines belong to a function or other code block; consistent indentation, commonly four spaces, improves readability.
- 37
Contrast printing a function's result with returning it.
Model answer
Printing displays output, whereas return sends a value out of a function so it can be stored or used in further computation.
Explanation
A function can print a message for immediate display, while return provides a result that can be stored and used in later operations.
- 38
How does a return value allow a function's result to be used in a later calculation?
Model answer
A function can return a calculated area, which can then be assigned to a variable and combined with other results.
Explanation
Returning the triangle's area makes that result available for later calculation, such as adding the areas of two triangles.
- 39
How could a function convert an hours-minutes-seconds input into a reusable total-seconds value?
Model answer
A function can accept hours, minutes, and seconds, calculate their total in seconds, and return that value for reuse.
Explanation
A function with hours, minutes, and seconds as parameters can calculate and return a total number of seconds for each set of inputs.
- 40
What is code reusability, and how does it save work?
Model answer
Reusability means defining code once and using it multiple times without rewriting it.
Explanation
Defining code once and calling it multiple times avoids rewriting the same logic for each input.
- 41
What is modularity, and how can it support collaboration?
Model answer
Modularity is the organization of code into separate components that work together and can be reused.
Explanation
Modularity separates a program into components that work together and can be reused in other programs or by collaborators.
- 42
How can a function improve a script that contains duplicated code?
Model answer
When the same operations appear repeatedly, group them into a reusable function to reduce duplication and improve clarity.
Explanation
A function can replace duplicated code, making a script shorter and easier to understand while preserving its behavior.
- 43
Define refactoring and self-documenting code, and explain how they relate.
Model answer
Refactoring restructures code while preserving behavior; self-documenting code is written so its purpose is clear from its organization and wording.
Explanation
Refactoring restructures code without changing its functionality; self-documenting code makes its purpose clear through readable names and expressions.
- 44
How does Python recognize a comment, and what purpose does commenting serve?
Model answer
A comment begins with # and is ignored by Python; it can document the code and explain the programmer's process to collaborators.
Explanation
A comment begins with #, which tells Python to ignore the remainder of that line; comments explain reasoning or workflow to human readers.
- 45
What information should a function's docstring communicate?
Model answer
A docstring is a string at the beginning of a function body that explains its behavior, inputs, and return value.
Explanation
A docstring is a string at the start of a function body, commonly enclosed in three quotation marks, that summarizes behavior and describes arguments and return values.
- 46
What is an algorithm, and how can comments help when designing one?
Model answer
An algorithm is a set of instructions for solving a problem or completing a task; comments can outline its steps before the code is written.
Explanation
An algorithm is a set of instructions for solving a problem or completing a task; breaking it into steps and outlining those steps in comments supports systematic problem solving.
- 47
What do comparator operators do, and which six comparisons are available in Python?
Model answer
Comparators compare values and return True or False; the six types test greater than, greater than or equal, less than, less than or equal, equal, and not equal.
Explanation
Comparator operators compare two values and yield Boolean results; Python's six comparison types test greater than, greater than or equal, less than, less than or equal, equality, and inequality.
- 48
Explain how and, or, and not combine or change Boolean expressions.
Model answer
and requires both expressions to be True, or requires at least one to be True, and not inverts the following Boolean value.
Explanation
The and operator returns True only if both connected expressions are True; or returns True if at least one is True; not reverses a Boolean result.
- 49
How does Python compare two strings using comparison operators?
Model answer
String comparisons proceed character by character from the beginning, moving to the next character when earlier characters match.
Explanation
When comparing strings, Python compares characters from left to right; if the first characters match, it proceeds to later characters.
- 50
When does the body of an if statement execute?
Model answer
An if statement executes its indented block only when its condition evaluates to True.
Explanation
An if statement runs its indented body only if its condition is True; otherwise, that body is skipped.
- 51
What does an else statement do, and how is it aligned with its if statement?
Model answer
An else block executes when the associated if condition is False and is aligned at the same indentation level as that if statement.
Explanation
An else block provides an alternative path when the preceding if condition is False, and it aligns with its corresponding if statement.
- 52
How do elif statements extend branching, and what is the role of a final else?
Model answer
Elif tests an additional condition when earlier conditions are False; a final else handles the remaining cases.
Explanation
Elif checks another condition when earlier conditions have failed, avoiding deeply nested if-else structures; a final else handles cases not covered above.
- 53
What is branching, and give one practical use for it in a data or business task.
Model answer
Branching selects which code to execute based on conditions, allowing programs to respond differently to different data or situations.
Explanation
Branching changes a program's execution path based on conditions and supports decisions such as validating usernames, grouping data, or controlling access.
- 54
How can the modulo operator be used to test whether an integer is even?
Model answer
Modulo returns a division remainder; a number is even when its remainder after division by two is zero.
Explanation
The modulo operator returns the remainder; a number divisible by two has remainder zero and can be identified as even.
- 55
How does a while loop determine whether to continue iterating?
Model answer
A while loop repeatedly executes its body as long as its condition is True, rechecking the condition after each iteration.
Explanation
A while loop repeats its indented body while its Boolean condition remains True, checking the condition again after each iteration.
- 56
Why must a while loop's condition be able to change, and how can a counter help?
Model answer
Update the state tested by the condition, such as incrementing a counter, so the condition can eventually become False and the loop can end.
Explanation
The loop's condition must eventually become False; incrementing a counter in the body can make that happen and prevent an infinite loop.
- 57
How does a for loop process the values of an iterable?
Model answer
A for loop iterates through an iterable one value at a time and assigns each value to its loop variable.
Explanation
A for loop visits values in a sequence or other iterable, assigning each current value to its loop variable for that iteration.
- 58
Define iteration and iterable, and explain how they relate to a loop.
Model answer
An iteration is one execution of a set of statements; an iterable is an object whose values can be traversed by a loop.
Explanation
An iteration is one execution of a block, an iterable is the object being traversed, and a loop carries out repeated iterations.
- 59
How does range determine its starting value, step, and stopping point by default?
Model answer
range generates numbers from a start value, uses a step of one by default, and excludes the stop value.
Explanation
range begins at zero by default, increments by one by default, and stops before its stop value; start and step parameters can change the sequence.
- 60
How would you include 100 as the final value in a range stepping by tens from zero?
Model answer
Set the stop value one greater than the desired final value when that final value needs to be included.
Explanation
To include a desired endpoint in a range, the stop value must be set one beyond it because the stop value is excluded.
- 61
When is a for loop preferable to a while loop, and when is a while loop preferable?
Model answer
Use a for loop to process a sequence of items and a while loop to repeat until a condition changes; either can be used when both fit.
Explanation
A for loop suits a known sequence or fixed set of items; a while loop suits repetition that continues until a Boolean condition changes.
- 62
Why should a numeric guess received from input be converted before comparing it with an integer target?
Model answer
Convert numeric input from string to integer before comparing it with an integer target, or their types will not match.
Explanation
An input function returns user input as a string. Converting a numerical guess to an integer allows it to be compared with an integer target.
- 63
In a limited-guess loop, what roles can a counter, break, and the += 1 shorthand play?
Model answer
A counter tracks attempts, break exits the loop, and += 1 increments a variable by one and assigns the result back to it.
Explanation
A counter tracks attempts; break exits a loop early when a success or limit condition is met; += 1 is a shorter form of adding one and reassigning.
- 64
What is a nested loop, and how can it generate combinations such as domino values?
Model answer
A nested loop is a loop inside another loop; the inner loop runs for each iteration of the outer loop.
Explanation
A nested loop places one loop inside another, allowing the inner process to run for each iteration of the outer loop.
- 65
How can strings be concatenated or repeated, and what must be considered when joining words?
Model answer
Concatenation joins strings with +, and multiplication repeats a string; include a whitespace character if joined text needs a space.
Explanation
Strings are immutable, but concatenation and repetition create new strings; whitespace is a character, so a space must be included explicitly to separate joined words.
- 66
How can a string contain quotation marks without ending prematurely?
Model answer
Enclose a string in the opposite quote type or escape an internal quote with a backslash.
Explanation
Python can include quote marks by enclosing a string in the other kind of quote or by escaping the quote with a backslash.
- 67
What is an escape character, and how does the backslash-n sequence behave in a string?
Model answer
A backslash is an escape character that changes how following characters are interpreted; \n marks a new line, while an escaped backslash lets it be shown literally.
Explanation
A backslash changes how the following character or sequence is interpreted; \n represents a new line, and an extra backslash can make the sequence appear literally.
- 68
Explain zero-based and negative indexing for a string.
Model answer
Python uses zero-based indexing: the first character has index zero, while negative indices count from the end, with negative one referring to the last character.
Explanation
Indexing locates individual elements by position; Python starts counting at zero, and negative indices count backward from the end.
- 69
What does the string index method return, and what errors may occur when a match or position is absent?
Model answer
The index method returns the first matching position and raises a ValueError if no match exists; an out-of-range position raises an IndexError.
Explanation
The index method returns the first matching location and raises a ValueError if the requested substring is absent; accessing a nonexistent index raises an IndexError.
- 70
How do slice endpoints work, including when one endpoint is omitted?
Model answer
A slice includes its start position but excludes its stop position; an omitted start defaults to the beginning and an omitted stop to the end.
Explanation
A slice uses a start and stop separated by a colon; the start is included and the stop excluded, and omitting either endpoint uses the beginning or end of the string.
- 71
How can you test whether a substring occurs in a string?
Model answer
Use in to test whether a substring occurs within a string; the result is True or False.
Explanation
The in keyword checks whether one string occurs as a substring in another and returns a Boolean result.
- 72
How does string formatting insert values into placeholders, and how do positional and named fields differ?
Model answer
The format method inserts values into brace placeholders; arguments can fill placeholders by position or by matching named fields.
Explanation
The format method inserts values where braces appear; positional arguments fill braces in order, while named fields match values by keyword.
- 73
Why can named string-format placeholders be useful when adapting text to different word orders?
Model answer
Named placeholders match each value to a labeled field, allowing the argument order to differ from the order in the output string.
Explanation
Named placeholders allow values to be placed according to labels rather than argument order, which makes it easier to rearrange text for different word orders.
- 74
How can string formatting improve the readability of numerical output?
Model answer
String formatting can limit decimal places with a specification such as .2f and align text within a field using a width specification.
Explanation
Formatting specifications can control decimal places with a form such as .2f and align output using a greater-than marker followed by a width.
- 75
Compare lists and strings in terms of contents, ordering, duplicates, and indexing.
Model answer
A list is an ordered sequence of elements that may have different types; a string is an ordered sequence of characters. Both allow duplicates, indexing, and slicing.
Explanation
Lists are ordered sequences that can hold items of different data types, while strings are ordered sequences specifically of characters; both support indexing, slicing, and duplicates.
- 76
Contrast the mutability of lists and strings.
Model answer
Lists are mutable and can be modified in place; strings are immutable and cannot be changed in place.
Explanation
Lists are mutable, allowing their elements to be changed, added, or removed; strings are immutable and cannot be altered in place.
- 77
How are Python lists written, indexed, and sliced?
Model answer
Create a list with square brackets and comma-separated elements; use zero-based indices to select an element and slices to select a range.
Explanation
Lists use square brackets and commas; indexing starts at zero, and slices use a start and stop with the stop excluded.
- 78
How do append and insert differ when modifying a list?
Model answer
append adds an element to the end of a list; insert places an element at a specified index.
Explanation
append adds one element at the end; insert takes an index and an element and places the element at that position.
- 79
Compare the remove and pop list methods.
Model answer
remove deletes a specified value, while pop removes an element by index; removing a value that is absent raises a ValueError.
Explanation
remove deletes a matching element by value and raises a ValueError if absent; pop removes and returns an element at a specified index.
- 80
How can an element of a list be replaced, and why does the same approach fail for a string?
Model answer
Replace a list element by assigning to its index; an equivalent in-place character replacement fails for a string because strings are immutable.
Explanation
A list element can be replaced by assigning a new value at its index; assigning to an indexed string character fails because strings are immutable.
- 81
Define a tuple and describe two ways to create one.
Model answer
A tuple is an immutable sequence that can contain values of different types; create one with parentheses or the tuple function.
Explanation
A tuple is an immutable ordered sequence and can contain different data types; it can be created with parentheses or the tuple function.
- 82
How can tuple data be changed or created from a list if tuples are immutable?
Model answer
A tuple's contents cannot be changed in place; make a modified tuple and reassign it, or convert another iterable with tuple.
Explanation
Changing a tuple requires creating and assigning a new tuple; it can also be converted from another iterable using tuple.
- 83
What does it mean to unpack a tuple returned by a function?
Model answer
Multiple returned values are grouped in a tuple, and unpacking assigns each tuple element to a separate variable.
Explanation
A function that returns several values returns them together as a tuple; assigning that tuple's elements to separate variables is unpacking.
- 84
Why might a data professional store records as tuples inside a list?
Model answer
Use a list for a collection that may be reordered or extended and tuples for individual records whose elements are intended to stay fixed.
Explanation
A list can hold mutable player records or other collections, while tuples can represent records whose fields should not be changed accidentally.
- 85
What must be true about the number of loop variables when unpacking tuples?
Model answer
Use one loop variable per tuple element when unpacking; the number of variables must match the tuple's length.
Explanation
A loop can unpack each tuple into a matching number of variables; a mismatch between tuple length and variables causes an error.
- 86
What is a list comprehension, and how does it relate to a for loop?
Model answer
A list comprehension creates a new list by applying an expression to each item in an iterable.
Explanation
A list comprehension constructs a new list from an expression applied to each item of an iterable, using a compact form of a loop.
- 87
How does a dictionary lookup work, and why can it not be used to search for a key from a value?
Model answer
A dictionary maps keys to values; indexing by a key retrieves its value, but indexing by a value does not search for its key.
Explanation
A dictionary stores key-value pairs; looking up a key retrieves its associated value, whereas looking up a value as if it were a key causes a key error if no such key exists.
- 88
Describe two ways to create a dictionary and how to add a new entry.
Model answer
Create a dictionary with braces and key-value pairs or with dict; add a pair by assigning a value to a new key.
Explanation
Dictionaries can be created with braces and colon-separated pairs or with dict; adding a new key-value pair uses assignment to that key.
- 89
State key constraints and lookup behaviors for Python dictionaries.
Model answer
Dictionary keys must be immutable; dictionaries are accessed by keys rather than positional indices, and in tests for key membership.
Explanation
Dictionary keys must be immutable, such as strings, numbers, or tuples; dictionaries have no positional ordering for index-based access, and in checks keys rather than values.
- 90
What do the keys, values, and items dictionary methods provide?
Model answer
A dictionary loop iterates over keys by default; keys returns keys, values returns values, and items returns key-value pairs.
Explanation
A dictionary loop visits keys by default; keys, values, and items provide access to keys, values, or key-value pairs, respectively.
- 91
How can a dictionary organize multiple player records by position?
Model answer
Use each category as a key and store its records in a list; check whether the key exists before appending or creating the value.
Explanation
A dictionary can group multiple records under one key by storing a list of tuples as its value; conditional logic can check whether to append to an existing group or create it.
- 92
Describe the ordering, uniqueness, and mutability properties of sets.
Model answer
A set is an unordered collection of unique elements; the set can be modified, but its elements must be immutable, so a set cannot serve as a dictionary key.
Explanation
Sets contain unique unordered elements; set itself is mutable, while its elements must be immutable, so sets cannot be dictionary keys.
- 93
How does set remove duplicates, and how do you create an empty set?
Model answer
Use set(iterable) to create a set of unique elements; use set() for an empty set because empty braces create a dictionary.
Explanation
set accepts an iterable and keeps only unique elements; an empty pair of braces denotes a dictionary, so set() creates an empty set.
- 94
What is the difference between creating a set from a string with set() and placing a string in braces?
Model answer
set(string) produces unique individual characters, while braces around a string literal create a set whose single element is that whole string.
Explanation
Passing a string to set treats the string as an iterable of characters, keeping each unique character once; brace notation instead treats a quoted string as one set element.
- 95
Why can a set not be indexed or sliced?
Model answer
A set cannot be indexed or sliced because its elements are unordered rather than positionally arranged.
Explanation
Sets are unordered and their elements are not positionally accessible, so indexing and slicing do not apply.
- 96
Explain intersection, union, and difference for sets.
Model answer
Intersection finds shared elements, union combines the elements, and difference finds elements in the first set but not the second.
Explanation
Intersection returns shared elements, union returns elements from either set, and difference returns elements in the first set but not the second.
- 97
How does symmetric difference differ from ordinary set difference?
Model answer
Difference is directional, while symmetric difference returns all elements that the two sets do not share.
Explanation
Difference depends on the order of subtraction; symmetric difference instead returns elements present in either set but not shared by both.
- 98
What is a Python library or package, and how are the terms commonly used?
Model answer
A library or package is a reusable code collection that can include modules and documentation; the terms are often used interchangeably.
Explanation
Libraries and packages broadly refer to reusable code collections; they contain or provide access to modules and documentation, and the terms are often used interchangeably.
- 99
What does a Python module contain, and what does importing it allow you to do?
Model answer
A module is a Python file containing items such as functions, classes, and global variables that can be imported into a program.
Explanation
Modules are Python files containing functions, classes, and global variables; importing them makes prewritten components available to a script.
- 100
What distinguishes a global variable, and what are the math and random modules used for?
Model answer
Global variables are accessible throughout a program; math provides mathematical functions, and random supports random numbers and random selection.
Explanation
Global variables can be accessed throughout a program or script; math supplies mathematical functions, while random supports random-number and random-selection tasks.
- 101
Compare the visualization roles of matplotlib and seaborn.
Model answer
Matplotlib provides tools for static, animated, and interactive visualizations; seaborn builds on it with a simpler interface for common plots.
Explanation
Matplotlib supports static, animated, and interactive visualizations; seaborn is built on matplotlib and offers a simpler interface for common plots.
- 102
Contrast the main purposes of NumPy and pandas.
Model answer
NumPy supports numerical computation with arrays and matrices; pandas builds on NumPy to work with tabular data.
Explanation
NumPy provides multidimensional arrays, matrices, and operations for scientific computation; pandas builds on NumPy to manipulate and analyze tabular data.
- 103
What kinds of work do scikit-learn and statsmodels support?
Model answer
scikit-learn and statsmodels provide tools for statistical modeling, including functions to test model performance.
Explanation
scikit-learn and statsmodels provide functions for testing statistical model performance and are used across scientific fields.
- 104
What do import statements and aliases do, and what is the standard NumPy alias?
Model answer
An import statement loads a library, package, module, or function; aliasing gives it an alternate name, with np the standard NumPy alias.
Explanation
An import statement loads an external component into the computing environment; aliasing assigns it a shorter alternate name, and np is the standard NumPy alias.
- 105
What is vectorization, and why is it useful for large datasets?
Model answer
Vectorization performs an operation across multiple data elements at once, often making computations faster and more memory-efficient than element-by-element loops.
Explanation
Vectorization applies an operation to multiple data components together, rather than iterating through elements one at a time, improving speed and memory efficiency for large data.
- 106
How can NumPy simplify element-wise multiplication of two lists?
Model answer
Convert compatible lists to NumPy arrays and use an operator to perform an element-wise operation across corresponding values.
Explanation
NumPy arrays support element-wise operations when the arrays are compatible; converting lists to arrays can replace a manual loop for element-wise multiplication.
- 107
What is an ndarray, and how can one be created and modified?
Model answer
An ndarray is NumPy's N-dimensional array; create one with np.array and modify an existing element by assigning at its index.
Explanation
The ndarray is NumPy's core N-dimensional array structure; it can be created by passing a Python object to np.array and its values can be changed by index.
- 108
What restrictions apply to changing an ndarray's size and to the data types of its elements?
Model answer
A NumPy array is mutable in its values but not in its size; changing its length requires reassignment, and its elements share a common data type.
Explanation
An array's element values can be changed, but changing its length requires assigning a new array; NumPy arrays generally coerce elements to a common data type.
- 109
What do the type, dtype, shape, and ndim checks tell you about an array, and what does reshape do?
Model answer
Use type for the object class, dtype for element type, shape for dimensions, ndim for dimension count, and reshape to change the arrangement.
Explanation
type reports the array object as a NumPy array; dtype describes the element type, shape gives its dimensions, ndim gives the number of dimensions, and reshape changes its dimensions when compatible.
- 110
What is pandas primarily designed to do, and what is a DataFrame?
Model answer
Pandas is a library for manipulating and analyzing tabular data; its DataFrame represents data in rows and columns and can be loaded from sources such as CSV files.
Explanation
Pandas is designed for tabular data and can read sources such as CSV files, spreadsheets, and databases; a DataFrame is its two-dimensional table-like structure.
- 111
Compare pandas DataFrames and Series.
Model answer
A DataFrame is a labeled two-dimensional structure with rows and columns; a Series is a labeled one-dimensional structure often used for one row or column.
Explanation
A DataFrame is two-dimensional and labeled, while a Series is one-dimensional and labeled; a single DataFrame row or column is often represented as a Series.
- 112
How can a DataFrame be created from a dictionary or a NumPy array?
Model answer
Use pandas DataFrame to construct a table from sources such as a dictionary of column data or a two-dimensional NumPy array.
Explanation
DataFrame can create a table from data such as a dictionary, where keys name columns and lists provide row values, or from a two-dimensional NumPy array.
- 113
What is a CSV file, and how can pandas load one?
Model answer
A CSV is a plaintext file with comma-separated values; pandas read_csv loads one from a URL or a file path.
Explanation
CSV is a plaintext format in which commas separate values; pandas read_csv can read a CSV from a URL or a local file path.
- 114
What information do a DataFrame's columns, shape, and info provide?
Model answer
Use columns for column labels, shape for dimensions, and info for a summary of column types, non-null counts, and memory use.
Explanation
columns gives column labels, shape gives row and column counts, and info reports details such as column names, data types, non-null counts, and memory use.
- 115
How does pandas represent missing values, and what type may be reported for mixed or string Series data?
Model answer
Pandas uses NaN to represent null values, and a mixed or string Series may report its data type as object.
Explanation
Pandas represents null values with NaN; a Series containing mixed or string data may have the general object data type.
- 116
How can you select one or several named columns from a DataFrame?
Model answer
Select one column with brackets or compatible dot notation; select multiple columns by passing a list of names inside brackets.
Explanation
A single named column can be selected with brackets or, when its name has no whitespace, dot notation; a list of column names in brackets selects multiple columns.
- 117
How does iloc select rows, and how does the result differ for an integer versus a list of one integer?
Model answer
iloc selects by integer location; an integer returns a row as a Series, while a list containing the integer returns a one-row DataFrame.
Explanation
iloc selects by integer position; a single integer selects a row as a Series, while a list containing that integer selects a one-row DataFrame.
- 118
Compare loc and iloc, including how iloc handles a range of positions.
Model answer
iloc selects by integer position with the stop excluded; loc selects by row and column labels.
Explanation
iloc ranges include the start position and exclude the stop; row and column positions can be combined, and loc selects using labels instead of integer positions.
- 119
How does Boolean masking filter a DataFrame, and does applying a mask alone permanently change the original?
Model answer
Create a Boolean Series from a condition and use it to select rows marked True; assign the result if you want to retain the filtered result under a name.
Explanation
Boolean masking creates a Boolean Series from a condition and uses it to keep rows marked True and filter out rows marked False; filtering alone produces a view unless assigned.
- 120
Which symbols combine multiple Boolean conditions in pandas, and how should the conditions be grouped?
Model answer
Use & for and, | for or, and ~ for not in pandas masks, enclosing each condition in parentheses.
Explanation
Pandas combines Boolean conditions using &, |, and ~ for and, or, and not; each condition should be enclosed in parentheses.
- 121
What does groupby do, and what kinds of calculations can be applied to its groups?
Model answer
groupby partitions rows by values in specified columns, after which aggregation methods can summarize each group.
Explanation
groupby creates groups based on the values of one or more columns; methods such as sum, mean, min, max, median, or count can then summarize them.
- 122
How can pandas group by more than one column and summarize each group with multiple calculations?
Model answer
Group by multiple columns to separate distinct combinations of their values, then use agg to apply multiple summaries to each group.
Explanation
Grouping by multiple columns creates groups for each distinct combination of their values; agg can apply several calculations to the resulting groups.
- 123
How can agg apply both built-in summaries and a custom-defined calculation?
Model answer
Use agg with names of existing aggregation methods or pass a custom function to calculate a statistic not provided directly.
Explanation
agg can apply existing calculations named as strings or a custom-defined function; a custom percentile function can be supplied as a function object.
- 124
How does the axis argument control the direction of pandas concat?
Model answer
Use concat to combine DataFrames; axis 0 adds rows vertically, while axis 1 adds columns horizontally.
Explanation
concat can add data vertically as rows or horizontally as columns; axis 0 extends vertically and axis 1 extends horizontally.
- 125
What can happen to row indices after vertical concatenation, and how can they be reset without keeping the old index as a column?
Model answer
After vertical concatenation, reset_index can create consecutive row indices; use drop=True to avoid adding the old index as a column.
Explanation
Concatenating identically structured tables vertically retains original indices by default; resetting the index can create a new consecutive index, and drop=True prevents the old index from becoming a column.
- 126
Define inner, outer, left, and right joins in terms of which keys they retain.
Model answer
merge joins on shared keys: inner keeps keys in both tables, outer keeps all keys, left keeps all left-table keys, and right keeps all right-table keys.
Explanation
merge joins DataFrames horizontally based on common keys; inner keeps shared keys, outer keeps all keys, left keeps all left keys, and right keeps all right keys.
- 127
What happens to unmatched rows and fields in an outer join?
Model answer
An outer join retains unmatched keys from both tables and fills the unavailable fields for those rows with NaN.
Explanation
Rows without a matching key in one input have missing values for that input's columns in an outer join; pandas represents those missing values as NaN.
- 128
What three structural rules define a tidy dataset?
Model answer
A tidy dataset has one variable per column, one observation per row, and one type of observational unit per table.
Explanation
Tidy data makes analysis easier: each variable is a column, each observation is a row, and each type of observational unit is a table.
- 129
What is the goal of preparing unstructured files for a business-focused data project, and why document the process?
Model answer
Prepare data for its business purpose by loading, cleaning, and structuring it into a tidy dataset, and document the decisions and steps taken.
Explanation
A data professional may load, clean, and structure unstructured files into a tidy dataset suited to a business scenario; documenting decisions helps explain the process and thought behind the work.
- 130
How can Python support multiple stages of a data workflow, and what is one benefit of automating repetitive tasks?
Model answer
Python supports tasks such as data exploration, cleaning, visualization, and model building; automating repeated work can save time for analysis and insight generation.
Explanation
Python can support data professionals across the workflow, including exploring, cleaning, visualizing, and modeling data; automation can reduce repeated work and leave more time for generating insights.
- 131
How can clean code and audience-aware communication support a data project or its presentation?
Model answer
Readable, reusable code supports collaboration and reduces errors; when explaining a project, adapt the technical detail to the audience's goals and knowledge.
Explanation
Clean, reusable code can improve collaboration, reduce errors, and help a team work and communicate more effectively; interview explanations should also account for the audience's technical knowledge and needs.

Ask anything
We've read this whole study set, so questions about it get the best answers.