Comprehensions Flashcards
List the 4 types of Comprehensions
1) List comprehension - [ ]
2) Set comprehension - { }
3) Dict comprehension - {key : value}
4) Generator expression - ( )
Which type of comprehension is significantly more memory-efficient, and why
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.
On average, how much faster are “comprehensions” pocessed than an equivalent “for” loop
About 1.5x to 2.5x faster on average
Are comprehensions considered to be more “Pythonic”
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.
When does using comprehensions hurt readability
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]
x for x in items
Write the above as a,
1) List comprehension
2) Generator expression
Explain the difference
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
result = []
for x in range(5):
result.append(x * 2)
Convert the above to list comprehension
result = [x * 2 for x in range(5)]
result = []
for x in range(10):
if x % 2 == 0:
result.append(x)
Convert the above to list comprehension
result = [x for x in range(10) if x % 2 == 0]
words = [“hi”, “hello”, “hey”, “world”]
result = []
for word in words:
if len(word) > 3:
result.append(word)
Convert the above to list comprehension
result = [word for word in words if len(word) > 3]
nums = [1, 2, 3, 4, 5]
result = []
for num in nums:
result.append(num ** 2)
Convert the above to list comprehension
result = [num ** 2 for num in nums]
names = [“Alice”, “Bob”, “Charlie”]
result = []
for name in names:
result.append(name.upper())
Convert the above to list comprehension
result = [name.upper() for name in names]
result = []
for x in range(10):
if x % 2 != 0:
result.append(x ** 3)
Convert the above to list comprehension
result = [x ** 3 for x in range(10) if x % 2 != 0]
words = [“apple”, “banana”, “cherry”]
result = []
for word in words:
result.append(word[0])
Convert the above to list comprehension
result = [word[0] for word in words]
sentence = “hello world”
result = []
for char in sentence:
if char != “ “:
result.append(char)
Convert the above to list comprehension
result = [char for char in sentence if char != “ “]
result = []
for x in range(1, 6):
result.append(str(x))
Convert the above to list comprehension
result = [str(x) for x in range(1, 6)]
nums = [2, 4, 6, 8]
result = []
for n in nums:
if n > 5:
result.append(n)
Convert the above to list comprehension
result = [n for n in nums if n > 5]
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
result = [num for row in matrix for num in row]
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
result = [“even” if n % 2 == 0 else “odd” for n in nums]
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
result = [f”{name} is {age}” for name, age in zip(names, ages)]
items = [“apple”, “banana”]
result = []
for i, item in enumerate(items):
result.append(f”{i}: {item}”)
Convert the above to list comprehension
result = [f”{i}: {item}” for i, item in enumerate(items)]
text = “H,e.l!l:o?”
result = []
for c in text:
if c.isalpha():
result.append(c)
Convert the above to list comprehension
result = [c for c in text if c.isalpha()]
What’s the #1 reason to use a List Comprehension instead of a Generator Expression, and why
You need to use the result more than once
Because a generator expression can only be looped through once
result = []
for char in “String”:
result.append(char * 2)
print(‘‘.join(result))
Convert the above to a Generator expression
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().