Showing 41–50 of 119 questions
Consider: *a, b = [1, 2, 3]. What is a?
A
[1, 2]
B
1
C
[1, 2, 3]
D
Error
Correct Answer:
A. [1, 2]
EXPLANATION
The * operator in unpacking collects remaining elements. a gets [1, 2] and b gets 3.
What will be the result of: set([1, 2, 2, 3, 3, 3])?
A
{1, 2, 2, 3, 3, 3}
B
{1, 2, 3}
C
[1, 2, 3]
D
Error
Correct Answer:
B. {1, 2, 3}
EXPLANATION
Sets remove duplicate elements. set([1, 2, 2, 3, 3, 3]) returns {1, 2, 3}.
Consider: f = lambda x: x**2. What is f(5)?
EXPLANATION
Lambda creates an anonymous function. f = lambda x: x2 creates a function that returns x squared. f(5) = 52 = 25.
What is the output of: print(*[1, 2, 3])?
A
[1, 2, 3]
B
1 2 3
C
123
D
Error
EXPLANATION
The * operator unpacks the list. print(*[1, 2, 3]) becomes print(1, 2, 3) which prints '1 2 3' with spaces.
Consider: try: int('abc'); except: print('error'). What will be printed?
A
Nothing
B
'error'
C
error
D
ValueError
EXPLANATION
int('abc') raises a ValueError. The except block catches it and prints 'error' (without quotes).
What will be the output of: print('abc' * 3)?
A
'abc' 'abc' 'abc'
B
'abcabcabc'
C
abcabcabc
D
Error
Correct Answer:
C. abcabcabc
EXPLANATION
String multiplication repeats the string. 'abc' * 3 produces 'abcabcabc' and print displays it without quotes.
Consider: lst = [1, [2, 3], 4]. What is lst[1][0]?
EXPLANATION
lst[1] refers to the nested list [2, 3]. lst[1][0] refers to the first element of that nested list, which is 2.
Consider: d = {1: 'a', 2: 'b', 3: 'c'}. What is d.get(4, 'default')?
A
'c'
B
None
C
'default'
D
Error
Correct Answer:
C. 'default'
EXPLANATION
The get() method returns a value for a key. If the key doesn't exist, it returns the default value provided.
What will be the result of: ' hello '.strip()?
A
' hello'
B
'hello '
C
'hello'
D
'HELLO'
Correct Answer:
C. 'hello'
EXPLANATION
The strip() method removes leading and trailing whitespace. ' hello '.strip() returns 'hello'.
Consider: result = [x*2 for x in range(3) if x > 0]. What is result?
A
[0, 2, 4]
B
[2, 4]
C
[0, 1, 2]
D
[1, 2, 3]
Correct Answer:
B. [2, 4]
EXPLANATION
List comprehension iterates through range(3) [0,1,2], filters x>0 [1,2], and multiplies by 2: [2, 4].