Python Comprehensions
Python Comprehensions
Comprehensions in Python are concise and expressive ways to create data structures
like lists, dictionaries, and sets. They provide a more readable and efficient alternative
to traditional loops for generating such structures. Python comprehensions include list
comprehensions, dictionary comprehensions, and set comprehensions.
1. List Comprehensions: List comprehensions provide a compact way to generate lists. The basic syntax
is:
python
Copy code
Example:
python
Copy code
python
Copy code
Example:
python
Copy code
python
Copy code
expression, item, iterable, and condition have the same meanings as in list
comprehensions.
Example:
python
Copy code
Conciseness: They allow you to achieve the same result with less code, improving readability.
Performance: Comprehensions are generally faster than traditional loops.
Expressiveness: They make your code more expressive and Pythonic.
However, comprehensions might become less readable if they become too complex.
It's essential to strike a balance between conciseness and readability when using
comprehensions.
窗体顶端
窗体底端
MCQs
19. Which of the following is a valid way to use a comprehension with a tuple?
- A) `(x for x in range(5))`
- B) `{x for x in range(5)}`
- C) `[x for x in range(5)]`
- D) None of the above
- **Answer: D) None of the above**
21. Which of the following is a correct way to write a comprehension that generates a list of strings?
- A) `[str(x) for x in range(5)]`
- B) `{str(x) for x in range(5)}`
- C) `(str(x) for x in range(5))`
- D) `str(x) for x in range(5)`
- **Answer: A) `[str(x) for x in range(5)]`**
23. Which of the following comprehensions will create a list of lowercase letters from 'a' to 'z'?
- A) `[chr(x) for x in range(ord('a'), ord('z')+1)]`
- B) `{chr(x) for x in range(ord('a'), ord('z')+1)}`
- C) `(chr(x) for x in range(ord('a'), ord('z')+1))`
- D) None of the above
- **Answer: A) `[chr(x) for x in range(ord('a'), ord('z')+1)]`**
25]`
- D) `[4]`
- **Answer: B) `[4, 16]`**
- D) `{(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)}`
- **Answer: B) `{4, 16}`**
))`**