Learning Flashcards

(17 cards)

1
Q

What is a list comprehension?

A

A concise way to create lists.
squares = [x**2 for x in range(10)]

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

How do you handle exceptions in Python?

A

Use try, except, and optionally finally.
try:
result = 10 / 0
except ZeroDivisionError:
result = None

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

How do you use the set data type?

A

A collection of unique elements.
unique = set([1, 2, 2, 3])

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

How do you use the zip function?

A

Combine multiple iterables into tuples.
for a, b in zip([1, 2], [3, 4]):
print(a, b)

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

How do you use the global keyword?

A

Declare that a variable is global inside a function.
count = 0
def increment():
global count
count += 1

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

How do you use the sorted function with a custom key?

A

names = [“bob”, “alice”, “carol”]
sorted_names = sorted(names, key=lambda x: x.lower())

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

How do you use the filter function?

A

Filter items in an iterable based on a condition.
evens = list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4]))

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

How do you use the map function?

A

Apply a function to every item in an iterable.
result = list(map(str.upper, [“a”, “b”, “c”]))

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

How do you use the enumerate function?

A

Get both index and value when looping.
for i, value in enumerate([10, 20, 30]):
print(i, value)

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

How do you use the isinstance function?

A

if isinstance(x, dict):

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

How do you use the getattr function?

A

Safely get an attribute from an object, with a default.
email = getattr(user, “email”, None)

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

How do you handle missing data in pandas?

A

Use .dropna() to remove, or .fillna() to replace.
df = df.dropna()
df = df.fillna(0)

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

How do you rename columns in a pandas DataFrame?

A

df = df.rename(columns={“A”: “Alpha”, “B”: “Beta”})

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

How do you iterate over rows in a pandas DataFrame?

A

Use .iterrows() or .itertuples().
for idx, row in df.iterrows():
print(row[“A”])

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

How do you select rows in a pandas DataFrame based on a condition?

A

filtered = df[df[“A”] > 1]

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

How do you check if a key exists in a dictionary?

A

Use the in keyword.
if “name” in my_dict:
print(my_dict[“name”])