DATA 172: Python for Data Analysis Flashcards

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/58

flashcard set

Earn XP

Description and Tags

Comprehensive review flashcards covering dictionaries, random number generation, CSV parsing, JSON formatting, web APIs, matplotlib data visualization, NumPy multi-dimensional array manipulation, and Jupyter notebook workflows from DATA 172.

59 Terms

1
New cards

What is a Python dictionary, and what is the fundamental relationship between its keys and values?

A dictionary (dict) is a data structure that maps unique keys to values. Each individual key maps to exactly one value.

2
New cards

Why is looking up a key in a dictionary generally preferred over searching through a list of 1,000,0001{,}000{,}000 items?

Dictionary lookups are extremely fast because they execute in constant time (O(1)O(1)), whereas searching sequentially through an unsorted list of 1,000,0001{,}000{,}000 elements is significantly slower.

3
New cards

What exception is raised in Python when attempting to access a dictionary key that does not exist?

Python raises a KeyError.

4
New cards

What is the recommended style for iterating over a dictionary to access both keys and values, and why should myDict.items() be avoided?

The recommended style is for key in myDict: value = myDict[key]. Calling myDict.items() is discouraged because it creates an unnecessary intermediate step and can introduce bugs.

5
New cards

Why should you avoid calling myDict.update({key: value}) when adding or updating a single key-value pair?

Calling .update() with a newly constructed single-entry dictionary adds unnecessary overhead; direct assignment with myDict[key] = value is cleaner, faster, and standard Python style.

6
New cards

Why is using an if key not in myDict: check considered suboptimal when building an integer counter dictionary?

Using if key not in myDict: is clunky and requires up to 33 separate key lookups instead of 11, which can noticeably slow down code execution.

7
New cards

What is the preferred single-line pattern for incrementing an integer counter in a dictionary myDict for a given key?

myDict[key] = myDict.get(key, 0) + 1

8
New cards

What is the Brown corpus, when was it collected, and approximately how many words does it contain?

The Brown corpus is a famous linguistic corpus assembled in 19611961 consisting of approximately 1,000,0001{,}000{,}000 words compiled from scholarly writings, news articles, books, and other texts.

9
New cards

Why cannot a standard Python list serve as a dictionary key, and how can a programmer work around this limitation?

Dictionary keys must be immutable, whereas lists are mutable. The workaround is to convert the list to an immutable tuple (e.g., tuple(my_list)) and use the tuple as the key.

10
New cards

Why does the code curList = myDict.get(curKey, []); curList.append(curValue) fail to update myDict when curKey is missing?

The .get() method returns a new empty list default that is modified in memory, but that list is never actually assigned back to myDict[curKey], leaving the dictionary empty.

11
New cards

What is the recommended control flow structure for appending elements to list values within a dictionary when a key might not exist?

Using an explicit if check: if curKey not in myDict: myDict[curKey] = [] followed by myDict[curKey].append(curValue).

12
New cards

What mathematical constraint must always be satisfied by the probabilities of all possible outcomes for an event?

The probabilities of all possible outcomes must sum to exactly 11 (or 100%100\%).

13
New cards

How do random.randrange(a, b) and random.choice(myList) differ in functionality?

random.randrange(a, b) returns a randomly selected integer from aa (inclusive) up to bb (exclusive), whereas random.choice(myList) directly returns a randomly selected element from the provided sequence.

14
New cards

How does random.shuffle(myList) operate on its input, and what does it return?

random.shuffle(myList) reorders the elements of the passed list in-place and returns None.

15
New cards

How can you trigger an action with a specific probability of 0.81240.8124 using Python's random module?

By calling if random.random() < 0.8124:.

16
New cards

Why are computer-generated random numbers termed "pseudorandom," and how can a programmer make them repeatable across runs?

They are deterministic sequences produced by mathematical calculations starting from a seed value (typically based on system clock time). You can make them reproducible by setting a fixed seed using random.seed(number).

17
New cards

What does CSV stand for, and what structural guarantee does each row in a valid CSV file provide?

CSV stands for "Comma-Separated Values." Every line represents a record with a guaranteed consistent number of fields separated by commas.

18
New cards

Why is csv.DictReader generally preferred over csv.reader when parsing CSV files?

csv.DictReader automatically reads the first row as field names and parses each row as a dictionary mapped to those keys, making code more readable and resilient to column order changes.

19
New cards

When initializing a csv.DictWriter, what parameter prevents extraneous blank rows from appearing between entries on Windows, and what method must be called to output column headers?

Set lineterminator="\n" when creating the csv.DictWriter, and call writer.writeheader() to write the column names.

20
New cards

What does JSON stand for, and what structural advantage does it hold over CSV?

JSON stands for JavaScript Object Notation. Unlike flat tabular CSV structures, JSON naturally supports hierarchical, deeply nested data structures such as lists inside dictionaries.

21
New cards

What is the difference between Python's json.load() and json.loads() functions?

json.load() parses JSON directly from a readable file-like stream object, whereas json.loads() parses JSON data from a Python string.

22
New cards

What conversions happen to Python tuples, dictionary keys, and None when serialized into JSON?

Python tuples are converted into JSON lists/arrays, dictionary keys are coerced into strings, and None is translated into JSON null.

23
New cards

Which dedicated text editors were recommended by instructors Travis and Tom for inspecting complicated JSON structures instead of default Notepad?

Travis recommends Notepad++, while Tom recommends Sublime Text.

24
New cards

What does API stand for, and what is its role in software communication?

API stands for Application Programming Interface. It functions as a defined set of web functions or endpoints provided by a server to allow external code to request and receive data.

25
New cards

What do HTTP status codes 200200, 403403, and 404404 indicate?

200200 indicates "OK" (success), 403403 indicates "Forbidden" (access denied), and 404404 indicates "Page Not Found."

26
New cards

Why does the course explicitly advise using json.loads(response.text) rather than calling response.json() directly on a requests response object?

If the response payload is not valid JSON (e.g., an HTML error page), response.json() immediately crashes with an unhandled exception without allowing the programmer to inspect response.text.

27
New cards

Why must API keys never be hardcoded into public scripts or committed to repositories like GitHub?

Hardcoding exposes private credentials, risking costly server usage charges, quota exhaustion, and vulnerability to Denial of Service (DoS) attacks or credential theft.

28
New cards

In requests.post(), what is the difference between passing data=variable versus json=variable?

data=variable form-encodes the payload, whereas json=variable automatically serializes the data to JSON (equivalent to data=json.dumps(variable) with a JSON content-type header).

29
New cards

What standard alias is used throughout data science when importing matplotlib.pyplot?

import matplotlib.pyplot as plt

30
New cards

What effect does calling plt.show() have on script execution in a standard Python environment?

plt.show() displays a graphical window showing the plot and pauses further script execution until that window is closed.

31
New cards

Which matplotlib commands are used to explicitly enforce the display boundaries of the x-axis and y-axis?

plt.xlim([min, max]) sets the x-axis bounds, and plt.ylim([min, max]) sets the y-axis bounds.

32
New cards

What is the visual difference between saving plots in raster formats versus vector graphic formats using plt.savefig()?

Raster formats (PNG\text{PNG}, JPG\text{JPG}) are pixel-based and become pixelated when enlarged, whereas vector formats (SVG\text{SVG}, PDF\text{PDF}) scale infinitely without loss of sharpness.

33
New cards

How can multiple line series plotted with plt.plot() on the same axes be differentiated by the viewer?

Provide a descriptive name to each plot call using label="name" and then call plt.legend() to display the key.

34
New cards

How are colors from the xkcd color survey referenced in matplotlib function arguments?

They must be prefixed with xkcd:, such as color="xkcd:poo brown".

35
New cards

Which matplotlib linestyle string represents small, closely-spaced dots?

The ':' (colon) linestyle string.

36
New cards

What software design pattern is illustrated by evaluating if response.status_code != 200: to log an error and exit immediately rather than nesting deep if/else blocks?

A guard clause.

37
New cards

How do you plot multiple categories of bars side-by-side on the same matplotlib graph without overlapping?

Use numerical x-coordinates for bar centers, add or subtract an offset for each group, decrease the bar width, and label the positions using plt.xticks(intValues, stringLabels).

38
New cards

How can you rotate crowded x-axis tick labels to 45∘45^\circ and maintain clean alignment to their tick marks without clipping?

Call plt.xticks(xValues, labels, rotation=45, ha='right') and include plt.tight_layout() before displaying or saving.

39
New cards

In matplotlib's layout hierarchy, what is the conceptual difference between a Figure and an Axes?

A Figure is the overall top-level canvas or window (analogous to a picture frame), while an Axes is an individual plot or subplot containing data, tick marks, and labels (analogous to the painting inside the frame).

40
New cards

What commands clear current axes and figure contents to prevent subsequent calls to plt.savefig() from rendering stacked graphs?

plt.cla() (clear current axes) and plt.clf() (clear current figure).

41
New cards

How can subplot spacing in a multi-panel figure be reduced?

By calling fig.subplots_adjust(wspace=0.1, hspace=0.1).

42
New cards

What fundamental length restriction applies to NumPy arrays that does not apply to Python lists?

NumPy arrays have a fixed size; once created, their length cannot be changed and elements cannot be appended in-place with .append().

43
New cards

What are the three primary advantages of using NumPy arrays over native Python lists?

11) Compatibility with scientific computing and machine learning libraries, 22) Convenience of vectorized operations without explicit loops, and 33) Computational speed derived from its underlying C implementation.

44
New cards

How do arithmetic operations between two NumPy arrays of identical shape behave?

They operate strictly element-wise, matching corresponding indices and applying the operation across each pair of values.

45
New cards

How do you cast an existing NumPy array stringArr of string digits into an array of integers?

intArr = stringArr.astype(int)

46
New cards

What is the critical behavioral difference between slicing a standard Python list and slicing a NumPy array?

Slicing a list produces a new, independent copy, whereas slicing a NumPy array creates a view; modifying values inside an array slice directly alters the underlying original array.

47
New cards

What function is used to concatenate two NumPy arrays arr1 and arr2 together?

np.concatenate([arr1, arr2])

48
New cards

Which functions save and reload NumPy arrays to and from persistent storage, and what file format is used by default?

Arrays are saved using np.save('filename', myArray) and reloaded using np.load('filename.npy'), utilizing the .npy binary file extension.

49
New cards

What information is returned by the arr.ndim and arr.shape attributes of a NumPy array?

arr.ndim returns an integer indicating the total number of dimensions, whereas arr.shape returns a tuple specifying the size along each dimension.

50
New cards

What is the preferred syntax for indexing row rr and column cc in a 2D NumPy array?

arr[r, c]

51
New cards

What slice syntax extracts the entirety of the second column from a 2D NumPy array arr2d?

arr2d[:, 1]

52
New cards

Why is arr.ravel() preferred over arr.flatten() when flattening a multi-dimensional NumPy array into a 1D structure?

arr.ravel() returns a view without duplicating data in memory, whereas arr.flatten() always allocates a new copy.

53
New cards

Which operators must be used when combining multiple Boolean filtering conditions on a NumPy array, and what syntax requirement is mandatory?

Bitwise operators & (and), | (or), and ~ (not) must be used instead of Python keyword logical operators, and each individual condition must be enclosed in parentheses.

54
New cards

In what order are color channels organized when representing an image as a 3D NumPy array, and what value ranges are valid?

They are organized in RGB (Red, Green, Blue) order, with pixel intensity values bounded either between 00 and 255255 as integers (uint8) or between 0.00.0 and 1.01.0 as floating-point numbers.

55
New cards

What module and function load an image file into a NumPy array, and how can the resulting image array be darkened?

Load it with import matplotlib.image as mpimg; img = mpimg.imread("filename.png"). It can be darkened by multiplying the array by a scaling factor between 00 and 11.

56
New cards

What is JupyterLite, when was it released, and what storage constraint does it impose?

JupyterLite is a zero-installation browser-based deployment of Jupyter running Python via pyodide introduced in 20222022. It relies on browser storage, which limits files to a maximum size of 50 MB50\text{ MB}.

57
New cards

What functions do tab completion and the question mark (?) operator serve within interactive IPython sessions?

Pressing <tab> autocompletes variable names or displays callable methods/attributes, while entering ?<var> triggers introspection to show type, length, values, and docstrings.

58
New cards

How does rendering graphs inside a Jupyter notebook differ from traditional script execution with matplotlib?

Jupyter automatically displays plots directly beneath the code cell without requiring plt.show(), allowing code execution to proceed uninterrupted without pausing.

59
New cards

What file extension is used for saved Jupyter notebooks, and what does the file bundle together?

Notebooks are saved with a .ipynb extension and store formatted Markdown text, executable code blocks, equations, and cached output from the most recent run.