MCQ IN COMPUTER SCIENCE & ENGINEERING

COMPUTER SCIENCE AND ENGINEERING

DATA STRUCTURES

Question [CLICK ON ANY CHOICE TO KNOW THE RIGHT ANSWER]
Write a list comprehension to produce the list:[1, 2, 4, 8, 16 ____ 212].
A
[(2x) for x in range(0, 13)]
B
[(2x) for x in range(1, 13)]
C
[(x2) for x in range(0, 13)]
D
[(x2) for x in range(1, 13)]
Explanation: 

Detailed explanation-1: -Write a list comprehension to produce the list: [1, 2, 4, 8, 16…… 212]. Explanation: The required list comprehension will print the numbers from 1 to 12, each raised to 2. The required answer is thus, [(2**x) for x in range(0, 13)].

Detailed explanation-2: -1. What will be the output of the following Python code? Explanation: In the code shown above, each of the numbers of the list, that is, 1, 2, 3, 4 and 5 are AND-ed with 1 and the result is printed in the form of a list. Hence the output is [1, 0, 1, 0, 1].

Detailed explanation-3: -List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter “a” in the name.

Detailed explanation-4: -Explanation: The binary form of 1 is 0001. The expression x«2 implies we are performing bitwise left shift on x. This shift yields the value: 0100, which is the binary form of the number 4.

Detailed explanation-5: -List comprehension is an elegant way to define and create lists based on existing lists. List comprehension is generally more compact and faster than normal functions and loops for creating list. However, we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.

There is 1 question to complete.