Computer Science
Predict the output :
L1= [x ** 2 for x in range(10) if x % 3 == 0]
L2 = L1
L1.append(len(L1))
print(L1)
print(L2)
L2.remove(len(L2) - 1)
print(L1)
Python
Linear Lists
1 Like
Answer
[0, 9, 36, 81, 4]
[0, 9, 36, 81, 4]
[0, 9, 36, 81]
Working
L1 = [x ** 2 for x in range(10) if x % 3 == 0]
— This line creates a listL1
containing the squares of multiples of 3 between 0 to 9.L2 = L1
— This line assigns listL1
to listL2
, meaning bothL1
andL2
reference the same list in memory (shallow copy).L1.append(len(L1))
— This line appends the length ofL1
toL1
. So, the length ofL1
is 4, and it appends 4 toL1
.print(L1)
— This prints the modifiedL1
list.print(L2)
— This printsL2
, which is pointing to the same list asL1
.L2.remove(len(L2) - 1)
— This line removes the last element ofL2
sincelen(L2) - 1
gives the last index ofL2
.print(L1)
— This printsL1
again. Since bothL1
andL2
reference the same list, modifyingL2
also affectsL1
. Therefore,L1
also reflects the change made toL2
.
Answered By
3 Likes
Related Questions
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))
Predict the output :
ages = [11, 14, 15, 17, 13, 18, 25] print(ages) Elig = [x for x in ages if x in range(14, 18)] print(Elig)
Predict the output :
def even(n): return n % 2 == 0 list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] ev = [n for n in list1 if n % 2 == 0] evp = [n for n in list1 if even(n)] print(evp)
Predict the output.
b = [[9, 6], [4, 5], [7, 7]] x = b[:2] x.append(10) print(x)