File I/O in Python
15 questions · 12 min · Medium
Test your knowledge of list comprehensions in Python, including syntax, expressions, conditions, nested comprehensions, filtering, transformations, and common use cases.
No sign-up needed · Last updated:
Score: 0 00:00
Create a free account to keep your scores and track your progress. It is optional.
15 questions · 12 min · Medium
15 questions · 12 min · Medium
20 questions · 15 min · Medium
15 questions · 12 min · Medium
15 questions · 12 min · Medium
15 questions · 12 min · Medium
A. A concise way to create a list using an expression and an iterable
List comprehensions provide a compact syntax for creating lists by applying an expression to items from an iterable.
A. [expression for item in iterable]
The basic list comprehension syntax places the expression first, followed by the for clause.
A. [0, 2, 4, 6]
range(4) produces 0, 1, 2, and 3, and each value is multiplied by 2.
A. for
The for keyword introduces the iteration portion of a list comprehension.
A. By adding an if condition after the for clause
A filtering condition can be added after the for clause, such as [x for x in numbers if x > 0].
A. [0, 2, 4]
The condition keeps only values whose remainder when divided by 2 is zero.
A. [name.upper() for name in names]
The expression name.upper() is applied to each item produced by iterating over names.
A. [3, 4]
The values in range(5) are 0 through 4, and only 3 and 4 satisfy the condition x > 2.
A. Yes
List comprehensions can contain multiple for clauses, which can be useful for iterating over nested iterables.
A. [(1, 3), (1, 4), (2, 3), (2, 4)]
The nested for clauses produce every combination of an x value with a y value.
A. ["even" if x % 2 == 0 else "odd" for x in numbers]
A conditional expression can be placed in the expression portion of a list comprehension using the if-else syntax.
A. A list
List comprehensions always create and return a list.
A. A for loop that appends x * x to a list
The comprehension is a concise alternative to creating an empty list, looping through numbers, calculating x * x, and appending each result.
A. They can make simple list-building operations more concise
List comprehensions provide concise and readable syntax for many list construction and filtering tasks, although a regular loop may be clearer for complex logic.
A. [len(word) for word in words]
The len() function is applied to each word while iterating through the words iterable.