Intermediate Python Flashcards

Advanced level python

1
Q

How do you combine multiple .csv files into a single DataFrame?

A

Loop through each CSV file in the directory

Directory where the individual CSV files are saved
csv_directory = ‘/Users/Documents/Udacity/Political_News_2024/political_news’

Initialize an empty list to hold DataFrames
dataframes = []
for filename in os.listdir(csv_directory):
if filename.endswith(‘.csv’): # Check if the file is a CSV
file_path = os.path.join(csv_directory, filename)
df = pd.read_csv(file_path) # Save the CSV file
dataframes.append(df) # Append the DataFrame to the list
# Concatenate all DataFrames in the list
combined_news_df = pd.concat(dataframes, ignore_index=True)
# Get today’s date in YYYY-MM-DD format
today = datetime.today().strftime(‘%Y-%m-%d’)
# Define the path and name for the combined CSV file
combined_filename = os.path.join(csv_directory, f’combined_political_news_data_{today}.csv’)
# Save the combined DataFrame to CSV
combined_news_df.to_csv(combined_filename, index=False)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the steps to learning python

A

Learn the python language
Learn the standard library
Learn the ecosystem

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What three questions are asked to verify if data is a collection?

A

Can I know the size, or length, of this data? If so, the data is Sized.
Can I produce elements from this data set, one at a time? If so, the data is Iterable.
Can I check whether an element is in this data set? If so, the data is a Container.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What questions should you ask when thinking about structure, performance, and clarity?

A

Is the data ordered (sequential), or unordered?
Is the data associative, mapping between keys and values?
Is the data unique?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Define mutability

A

whether an object in Python can be changed after it has been created.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Define hashability

A

If all data in a collection is immutable. An object is hashable if it has a fixed hash value for its lifetime and it implements the __hash__() method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does false mean in Python

A

Something that is False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What means nothingness?

A

None

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Iterable

A

An object that can produce a stream of elements of data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Mapping

A

An unordered collection associating elements of data (keys) to other elements of data (values).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Set

A

An unordered collection of unique data elements

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Sized

A

An object that has a finite size

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Structured data

A

Information to which we assign meaning through organizaiton

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is a bool

A

Either False or True and encodes binary values

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are the numeric values for a number?

A

int (integer) or float (real)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is a string

A

An immutable sequence of text characters

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What represents nothingness

A

None

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What are the building blocks of data

A

bool
number
string
None

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How do you escape special characters in string literals

A

\
print(‘doesn't’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What does r”U\escaped” do?

A

It avoids ecaping, creating a raw string so special sequences U\escaped, \n (newline), or \t (tab) are treated as literal text, not as control characters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

name common methods for Strings

A
  • greeting.find(‘lo’) # 3 (-1 if not found)
  • greeting.replace(‘llo’, ‘y’) # => “Hey world!”
  • greeting.startswith(‘Hell’) # => True
  • greeting.isalpha() # => False (due to ‘!’)
  • greeting.lower() # => “hello world! “
  • greeting.title() # => “Hello World! “
  • greeting.upper() # => “HELLO WORLD! “
  • greeting.strip(‘dH !’) # => “ello worl”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Visualize how to convert the following:
str
int
float
bool

A

str(42) # => “42”
int(“42”) # => 42
float(“2.5”) # => 2.5
bool(None)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

T or F: converting a value to a bool turns it into a boolean

A

F: it gives the value an essence of truthiness

bool(None) # => False
bool(False) # => False
bool(41) # => True
bool(‘abc’) # => True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is a Python Object

A

A Python object can be thought of as a suitcase that has a type and contains data about its value. Everything in Python is an object.

isinstance(4, object) # => True
isinstance(“Hello”, object) # => True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Visualize how to evaluate a type function

A

type(1) # => <class ‘int’>
type(“Hello”) # => <class ‘str’>
type(int) # => <class ‘type’>
type(type(int)) # => <class ‘type’>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What are the characteristics of a Python Object?

A

everything in Python is an object
every Python object has a type
every Python object has an identity

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Visualize how to evaluate a Python object identity

A

id(41) # => 4361704848 (for example)
An object’s “identity” is unique and fixed during an object’s lifetime.* Python objects are tagged with their type at runtime and contain a reference to their blob of data

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What is a variable

A

a named reference to an object.
x = 5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What are namespaces?

A

A namespace (or symbol table) is an associative mapping from (variable) names to objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

How do you access namespaces

A

locals()
globals()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What is abstraction?

A

Distilling a concept to its core ideas so it can apply to multiple scenarios.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Name the four keys to thinking in abstraction

A

Generalization - dstilling a concept to core idea for widespread application
Simplication - removing unncessary details
Focus on Why - think about the goal
Reusability and scalability - desire is to reuse across multiple scenarios

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What comes after a dot (.)?

A

an attribute

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What is a name?

A

A reference to an object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What are Objects?

A

Bundles of data associated with actions. Basically everything in Python.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Visualize a Class Object

A

class ClassName:
<statement>
<statement>
<statement></statement></statement></statement>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What are elements?

A

A single unit of data that is Boolean, and a number or text.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What are ways to represent collections

A

Sets - unordered, unique data like tags for a blog
Sequences - ordered, non-unique or unique data like a list of tasks
Mappings -associative data like a product name with an id, country and a country code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

Container

A

An object that holds elements of data

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Mutable

A

A property of a data collection where the top-level collection can be changed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

Schema

A

A representation or outline of a data model

41
Q

Sequence

A

An ordered collection of data elements

42
Q

What is 5 ** 2

A

25.

** acts as square

43
Q

What is 7 // 2?

A

//Gives division with a floor.

44
Q

What are f-strings

A

a string literal prefixed with f or F, allowing for embedding expressions with {}
f”{x}”

45
Q

Visualize how to use the modulo operator for string interpolation

A

> > > name = “Jane”
“Hello, %s!” % name
‘Hello, Jane!’

46
Q

Visualize how to use a tuple with the modulo operator

A

> > > name = “Jane”
age = 25

> > > ” Hello, %s! You’re %s years old.” % (name, age)
‘Hello, Jane! You’re 25 years old.’

47
Q

Visualize how to use the str.format() method

A

> > > name = “Jane”
age = 25

> > > “Hello, {}! You’re {} years old.”.format(name, age)
“Hello, Jane! You’re 25 years old.”
or
“Hello, {1}! You’re {0} years old.”.format(age, name)
“Hello, Jane! You’re 25 years old.” ## uses indices to specify placements
or
“Hello, {name}! You’re {age} years old.”.format(name=”Jane”, age=25)
“Hello, Jane! You’re 25 years old.” ## improves readibility

48
Q

Visualize how to use dictionaries to provide values for interpolating strings

A

> > > person = {“name”: “Jane”, “age”: 25}

> > > “Hello, {name}! You’re {age} years old.”.format(**person)
“Hello, Jane! You’re 25 years old.”

49
Q

Visualize how to access strings by index

A

x = “string”
x[0] = “s”
x[-1] = “g”

50
Q

visualize slicing string sequences

A

x = “string”
x[0:2] = “st”

51
Q

what is slicing

A

Special syntax for accessing or updating elements or subsequences of data from a sequence type.

52
Q

What is str?

A

An immutable sequence of characters.

53
Q

what would
print(r”U\nescaped”) print?

A

U\nescaped

appending a r to the “” makes it a raw string, and ignores the escape. `

54
Q

visualize string conversions

A

float()
int()
str()
bool(False)

55
Q

What are false values

A

bool(None)
bool(0)
bool(0.9)
bool(“”)

56
Q

T or F: bool([False]) is False

A

False. It’s true because it contains something in it.

57
Q

Visualize how to remove a value from a list

A

list.remove(value)

58
Q

visualize how to return number of occurrences from a list

A

list.count(value)

59
Q

visualize how to return first index of value

A

list.index(value, [start, [stop]])

60
Q

visualize how to return item at index

A

list.pop([index])

61
Q

visualize how to sort in place

A

list.sort(key=None, reverse=False)
list.reverse()

62
Q

what is a list

A

a finite, ordered, mutable sequence of elements.
letters = [‘a’, ‘b’, ‘c’, ‘d’]

63
Q

visualize how to check if a str is an object

A

isinstance(“string”, object)
Return True if the object argument is an instance of the classinfo argument

64
Q

Visualize how to get an objects identity

A

id(x)
xxxxxxxx

65
Q

Visualize how to get the objects type

66
Q

what is a tuple?

A

an immutable sequence of arbitrary data.
v = ([1, 2, 3], [‘a’, ‘b’, ‘c’])

67
Q

translate s[1:5:2]
for
s = ‘Udacity’

A

go between positions 2 and 4, taking a step size of 2

s[1:5:2] = ‘dc’

68
Q

how do you reverse the elements of x?
x = ‘string’

A

x[::-1]
‘gnirts’

69
Q

how would you modify the list at index 3?
letters = [‘a’, ‘b’, ‘c’, ‘d’]

A

letters[2] = 3
letters = [‘a’, ‘b’, 3, ‘d’]

70
Q

visualize how to insert a value into a list

A

list.insert(x, index)

71
Q

T or F: s is a tuple
s = (‘value’)

A

False. A ‘,’ has to follow ‘value’ or it is s becomes a string.
s = (‘value’,)

72
Q

T or F: the below code would fail.
x = ([1,2,3], [‘a’,’b’,’c’])
x[0].append(4)
print(x)

A

False.
x = ([1,2,3], [‘a’,’b’,’c’])
x[0].append(4)
print(x)
Output
x = ([1,2,3,4], [‘a’,’b’,’c’])
Tuples aren’t immutable all the way down. You can modify what’s inside the lists.

73
Q

What does packing and unpacking mean?

A

Any comma-separated values are packed into a tuple:
t = 12345, 54321
print(t) # (12345, 54321)
type(t) # => tuple
Any comma-separated names unpack a tuple of values (which must be of the same size)
x, y = t
x # => 12345
y # => 54321

74
Q

Visualize variable-length tuple tuple packing/unpacking *start

A

Collect elements at the start
*start, x, y = (1, 2, 3, 4, 5)
print(start) # Output: [1, 2, 3]
print(x) # Output: 4
print(y) # Output: 5

75
Q

Visualize variable-length tuple packing/unpacking for *end

A

Collect elements at the end
a, b, *end = (1, 2, 3, 4, 5)
print(a) # Output: 1
print(b) # Output: 2
print(end) # Output: [3, 4, 5]

76
Q

Visualize variable-length tuple packing/unpacking using ignore

A

a, _, b, *rest = (1, 2, 3, 4, 5)
print(a) # Output: 1
print(b) # Output: 3
print(rest) # Output: [4, 5]

77
Q

Visualize variable-length tuple packing/unpacking using nesting

A

data = (1, 2, (3, 4, 5))
a, b, (x, *rest) = data
print(a) # Output: 1
print(b) # Output: 2
print(x) # Output: 3
print(rest) # Output: [4, 5]

78
Q

Visualize swapping using tuple packing/unpacking

A

x=5
y=6
x,y = y,x
Output:
x=6
y=5

79
Q

for sequence = [‘red’, ‘green’, ‘blue’]
Why is the code:
for index, value in enumerate(sequence):
print(index, value)
better than the code:
for i in range(len(sequence)):
print(i, sequence[i])

A

enumerate() directly provides both the index (index) and the corresponding value (value)
This is a form of tuple packing/unpacking

80
Q

Visualize how to make a string, list, or tuple

A

str([3, 4, 5]) # => ‘[3, 4, 5]’
list(“ABC”) # => [“A”, “B”, “C”]
tuple(“XYZ”) # => (“X”, “Y”, “Z”)

81
Q

Visualize how to use .split

A

‘ham cheese bacon’.split() # => [‘ham’, ‘cheese’, ‘bacon’]
‘03-30-2016’.split(sep=’-‘) # => [‘03’, ‘30’, ‘2016’]

82
Q

Visualize how to use .join

A

=> “Eric, John, Michael”

join creates a string from an iterable (of strings)
‘, ‘.join([‘Eric’, ‘John’, ‘Michael’])

83
Q

What is mapping?

A

using hashable values to:
-Encoding associative information
-Capturing plain data with named fields.
-Building more complicated data structures.

84
Q

Visualize the ways to create a dictionary

A

empty = {‘one’: ‘1’, ‘two’: 2, ‘three’ : 3}
dict(one = 1, two = 2, three = 3)

85
Q

Visualize ways to modify the dictionary

A

d = {“one”: 1, “two”: 2, “three”: 3}

Access and modify
d[‘one’] = 22

86
Q

Visualize how to use dict.get

A

temps = {‘CA’: [101, 115, 108], ‘NY’: [98, 102]}
temps.get(‘CA’) # => [101, 115, 108]
temps.get(‘KY’) # => None (not a KeyError!)

87
Q

What are ways to remove elements in dictionarys?

A

d = {“one”: 1, “two”: 2, “three”: 3}

del d[“one”]
d.pop(“three”, default) # => 3
d.popitem() # => (“two”, 2)
d.clear() #removes everything

88
Q

What is the .get()?

A

This method allows you to access a dictionary and specify a default value
a.get(‘five’, 0) #won’t have an error if five doesn’t exist.

89
Q

Visualize how to loop over the values in a dictionary

A

for v in x.values():
print(v)

90
Q

Visualize how to use a for loop to pack and unpack an dictionary

A

for key, value in x.items():
print(key,value)

91
Q

What methods allow you to view keys, values, or items?

A

d.keys()
d.values()
d.items()

92
Q

What is a set?

A

an unordered collection of distinct hashable elements
Can check: the size of, element containment, and loop over it

93
Q

Visualize a set

A

empty_set = set()
set_from_list = set([1, 2, 3, 2, 3, 4, 3, 1, 2]) # => {1, 2, 3, 4}
if you want to create a set, you have to use set()

94
Q

T or F: Sets can contain duplicates

A

False. Sets can only have unique values

95
Q

What are some set operations that you can use?

A

a = set(“mississippi”) # {‘i’, ‘m’, ‘p’, ‘s’}
a.add(‘r’)
a.remove(‘m’) # Raises a KeyError if ‘m’ is not present.
a.discard(‘x’) # Same as remove, except will not raise an error.
a.pop() # => ‘s’ (or ‘i’ or ‘p’)
a.clear()
len(a) # => 0

96
Q

Visualize how to use mathematical operations on sets

A

a = set(“abracadabra”) # {‘a’, ‘b’, ‘c’, ‘d’, ‘r’}
b = set(“alacazam”) # {‘a’, ‘m’, ‘c’, ‘l’, ‘z’}
# Set difference
a - b # => {‘b’, ‘d’, ‘r’}
# Union
a | b # => {‘a’, ‘b’, ‘c’, ‘d’, ‘l’, ‘m’, ‘r’, ‘z’}
# Intersection
a & b # => {‘a’, ‘c’}
# Symmetric Difference
a ^ b # => {‘b’, ‘d’, ‘l’, ‘m’, ‘r’, ‘z’}
# Subset
a <= b # => False

97
Q

What are the below named variations for the sets:
A. difference
B. union
C. intersection
D. symmetric difference

A

A. set.difference
B. set.union
C. set.intersection
D. set.symmetric_difference
E. set.issubset

98
Q

Comprehensions

A

A convenient shorthand to build lists, sets, or dictionaries
ex.
for x in range(6):
squares.append(x**2)

This is the comprehension [x***2 for x in range(6)]
print(squares)
[0,1,4,9,16,25,36)

99
Q

Visualize list comprehensions

A

[a transformation for an element in a collection (that meets criteria)]
[ x ** 2 for x in range(10) if x % 2 == 0]
# Lowercased versions of words in a sentence.
[word.lower() for word in sentence]
# Words in a sentence of more than 8 letters long.
[word for word in sentence if len(word) > 8]

100
Q

What is the dictionary comprehension syntax

A

{key_func(vars): value_func(vars) for vars in iterable}

101
Q

Visualize a dictionary comprehension

A

{student: grades for student, grades in gradebook.items() if sum(grades) / len(grades) > 90 builds a dictionary of student grades for students whose average grade is at least 90.