192 views
1 1 vote

Given a list of integers numbers $=[1,2,3,4,5,6]$, which of the following list comprehensions correctly creates a new list containing the squares of only the even numbers?

  1. numbers.map(lambda $x$ : $x^{\star \star} 2$ if $x \% 2==0$ )
     
  2. $x^{\star \star} 2$ for $x$ in numbers if $x \% 2==0]$
     
  3. $[x^{\star \star} 2$ if $x \% 2==0$ for $x$ in numbers $]$
     
  4. $\left[x^{\wedge} 2\right.$ for $x$ in numbers if $x \% 2==0$ ]

1 Answer

0 0 votes

A. numbers.map(lambda $\mathrm{x}: \mathrm{x} 2$ if $\mathrm{x} \% 2==0$ )**

  • INCORRECT: Python lists do not have a .map() method. You would need to use the built-in map() function.

B. $[\mathrm{x} 2 \text { for } \mathrm{x} \text { in numbers if } \mathrm{x} \% 2==0]^{* *}$

  • CORRECT: This follows the standard syntax: [expression for item in iterable if condition]. It correctly filters for even numbers and squares them.

C. $[x 2 \text { if } x \% 2==0 \text { for } x \text { in numbers }]^{* *}$

  • INCORRECT: When using if for filtering, it must come after the for clause. The if before the for is only used for ternary expressions (e.g., x if condition else y).

D. $\left[x^{\wedge} 2\right.$ for $x$ in numbers if $\left.x \% 2==0\right]$

  • INCORRECT: In Python, ${ }^{\wedge}$ is the bitwise XOR operator. The exponentiation operator is ** .
Answer:
Position:
Show:

Related questions

1 1 vote
1 1 answer
269
269 views
GO Classes asked Jan 1
269 views
 data = {'a': 1, 'b': 2, 'c': 3} for key in data: if data[key] 1: del data[key] print(len(data))What happens when this code is executed?It prints $1$ It prin...
1 1 vote
1 1 answer
231
231 views
GO Classes asked Jan 1
231 views
Predict the output of the following code:a = 256 b = 256 print(a is b) x = 257 y = 257 print(x is y)What is the output when run as a standard Python script?TRUE, TRUE TRU...
1 1 vote
1 1 answer
179
179 views
GO Classes asked Jan 1
179 views
What will be the output of the following Python code snippet?data = {'a': 10, 'b': 20} print(data.get('c', 30) + data.get('a'))KeyError $40$ $30$ $60$
2 2 votes
1 1 answer
308
308 views
GO Classes asked Jan 1
308 views
A GO Tree is a rooted binary tree defined as follows:For every node $u$ (except the root): Let parent $(u)$ be the parent of $u$.Define:$\operatorname{Side}(u)=0$ if $u$ ...