Computer Science
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))
Python
Linear Lists
2 Likes
Answer
5 [21, 12] 3
5 [21, 12] 3
[21, 12] 31 2
Working
def h_t(NLst):— This line defines a function namedh_tthat takes a single argumentNLst.from_back = NLst.pop()— This line removes and returns the last element from the listNLst, storing it in the variablefrom_back.from_front = NLst.pop(0)— This line removes and returns the first element from the listNLst, storing it in the variablefrom_front.NLst.append(from_front)— This line appends the value stored infrom_frontto the end of the listNLst.NLst.insert(0, from_back)— This line inserts the value stored infrom_backat the beginning of the listNLst.NLst1 = [[21, 12], 31]— This line initializesNLst1as a nested list.NLst3 = NLst1.copy()— This line creates a shallow copy ofNLst1and assigns it toNLst3.NLst2 = NLst1— This line assigns the reference ofNLst1toNLst2, meaning bothNLst1andNLst2point to the same list object.NLst2[-1] = 5— This line modifies the last element ofNLst2to 5. SinceNLst1andNLst2reference the same list object, this change also affectsNLst1.NLst2.insert(1, 6)— This line inserts 6 at index 1 inNLst2. Again, sinceNLst1andNLst2reference the same list object, this change also affectsNLst1.h_t(NLst1)— This line calls the functionh_twithNLst1as an argument.print(NLst1[0], NLst1[-1], len(NLst1))— This line prints the first element, last element, and length ofNLst1.print(NLst2[0], NLst2[-1], len(NLst2))— This line prints the first element, last element, and length ofNLst2.print(NLst3[0], NLst3[-1], len(NLst3))— This line prints the first element, last element, and length ofNLst3.
Answered By
3 Likes
Related Questions
Write equivalent for loop for the following list comprehension :
gen = (i/2 for i in [0, 9, 21, 32]) print(gen)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 :
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 :
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)