Computer Science
Write equivalent for loop for the following list comprehension :
gen = (i/2 for i in [0, 9, 21, 32])
print(gen)
Answer
In the above code, Python would raise an error because round brackets are used in list comprehension. List comprehensions work with square brackets only.
Explanation
The corrected code is:
gen = [i/2 for i in [0, 9, 21, 32]]
print(gen)
The equivalent for loop for the above list comprehension is:
gen = []
for i in [0, 9, 21, 32]:
gen.append(i/2)
print(gen)
Related Questions
Consider a list ML = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write code using a list comprehension that takes the list ML and makes a new list that has only the even elements of this list in it.
Write equivalent list comprehension for the following code :
target1 = [] for number in source: if number & 1: target1.append(number)
Predict the output of following code if the input is :
(i) 12, 3, 4, 5, 7, 12, 8, 23, 12
(ii) 8, 9, 2, 3, 7, 8
Code :
s = eval(input("Enter a list : ")) n = len(s) t = s[1:n-1] print(s[0] == s[n-1] and t.count(s[0]) == 0)
Predict the output :
def h_t(NLst): from_back = NLst.pop() from_front = NLst.pop(0) NLst.append(from_front) NLst.insert(0, from_back) NLst1 = [[21, 12], 31] NLst3 = NLst1.copy() NLst2 = NLst1 NLst2[-1] = 5 NLst2.insert(1, 6) h_t(NLst1) print(NLst1[0], NLst1[-1], len(NLst1)) print(NLst2[0], NLst2[-1], len(NLst2)) print(NLst3[0], NLst3[-1], len(NLst3))