Comprehensions Flashcards

1
Q

List the 4 types of Comprehensions

A

1) List comprehension - [ ]
2) Set comprehension - { }
3) Dict comprehension - {key : value}
4) Generator expression - ( )

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

Which type of comprehension is significantly more memory-efficient, and why

A

Generator expression

Because they don’t build and store a full result in memory - they yield one value at a time

Note that Generator Expressions are not faster than Comprehensions on average. But they are more memory efficient - particularily when handling large data.

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

On average, how much faster are “comprehensions” pocessed than an equivalent “for” loop

A

About 1.5x to 2.5x faster on average

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

Are comprehensions considered to be more “Pythonic”

A

Yes

“Pythonic” means writing code that follows the conventions, style, and spirit of Python — making it clean, readable, elegant, and efficient.

Essentially, it uses the language’s strengths instead of fighting them.

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

When does using comprehensions hurt readability

A

When the logic is too complex

e.g.,
[x if x % 2 == 0 else x * 3 for x in nums if x > 10 and x != 13]

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

x for x in items

Write the above as a,
1) List comprehension
2) Generator expression

Explain the difference

A

1) [x for x in items]
2) (x for x in items)

When printed,
1) List comprehension returns the form,
[False, True, False]
2) Generator expression return a generator object

Generator expressions produces items one item at a time, hence are more memory efficient when you don’t need the whole list

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

result = []
for x in range(5):
result.append(x * 2)

Convert the above to list comprehension

A

result = [x * 2 for x in range(5)]

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

result = []
for x in range(10):
if x % 2 == 0:
result.append(x)

Convert the above to list comprehension

A

result = [x for x in range(10) if x % 2 == 0]

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

words = [“hi”, “hello”, “hey”, “world”]
result = []
for word in words:
if len(word) > 3:
result.append(word)

Convert the above to list comprehension

A

result = [word for word in words if len(word) > 3]

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

nums = [1, 2, 3, 4, 5]
result = []
for num in nums:
result.append(num ** 2)

Convert the above to list comprehension

A

result = [num ** 2 for num in nums]

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

names = [“Alice”, “Bob”, “Charlie”]
result = []
for name in names:
result.append(name.upper())

Convert the above to list comprehension

A

result = [name.upper() for name in names]

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

result = []
for x in range(10):
if x % 2 != 0:
result.append(x ** 3)

Convert the above to list comprehension

A

result = [x ** 3 for x in range(10) if x % 2 != 0]

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

words = [“apple”, “banana”, “cherry”]
result = []
for word in words:
result.append(word[0])

Convert the above to list comprehension

A

result = [word[0] for word in words]

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

sentence = “hello world”
result = []
for char in sentence:
if char != “ “:
result.append(char)

Convert the above to list comprehension

A

result = [char for char in sentence if char != “ “]

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

result = []
for x in range(1, 6):
result.append(str(x))

Convert the above to list comprehension

A

result = [str(x) for x in range(1, 6)]

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

nums = [2, 4, 6, 8]
result = []
for n in nums:
if n > 5:
result.append(n)

Convert the above to list comprehension

A

result = [n for n in nums if n > 5]

17
Q

matrix = [[1, 2], [3, 4], [5, 6]]
result = []
for row in matrix:
for num in row:
result.append(num)

Convert the above to list comprehension

A

result = [num for row in matrix for num in row]

18
Q

nums = [1, 2, 3, 4]
result = []
for n in nums:
if n % 2 == 0:
result.append(“even”)
else:
result.append(“odd”)

Convert the above to list comprehension

A

result = [“even” if n % 2 == 0 else “odd” for n in nums]

19
Q

names = [“Alice”, “Bob”]
ages = [25, 30]
result = []
for name, age in zip(names, ages):
result.append(f”{name} is {age}”)

Convert the above to list comprehension

A

result = [f”{name} is {age}” for name, age in zip(names, ages)]

20
Q

items = [“apple”, “banana”]
result = []
for i, item in enumerate(items):
result.append(f”{i}: {item}”)

Convert the above to list comprehension

A

result = [f”{i}: {item}” for i, item in enumerate(items)]

21
Q

text = “H,e.l!l:o?”
result = []
for c in text:
if c.isalpha():
result.append(c)

Convert the above to list comprehension

A

result = [c for c in text if c.isalpha()]

22
Q

What’s the #1 reason to use a List Comprehension instead of a Generator Expression, and why

A

You need to use the result more than once

Because a generator expression can only be looped through once

23
Q

result = []
for char in “String”:
result.append(char * 2)
print(‘‘.join(result))

Convert the above to a Generator expression

A

result = ‘‘.join(char * 2 for char in “String”)
print(result)

The original method was already efficient, because .append adds new items to the list “in place” rather than creating a new object for every loop.

However, the Generator Expression version is slightly more efficient than building a list and joining it, because it avoids creating and storing a list in memory. Instead is yields each value one at a time to join().