KnowledgeBoat Logo

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

1 Like

Answer

5 [21, 12] 3
5 [21, 12] 3
[21, 12] 31 2

Working

  1. def h_t(NLst): — This line defines a function named h_t that takes a single argument NLst.
  2. from_back = NLst.pop() — This line removes and returns the last element from the list NLst, storing it in the variable from_back.
  3. from_front = NLst.pop(0) — This line removes and returns the first element from the list NLst, storing it in the variable from_front.
  4. NLst.append(from_front) — This line appends the value stored in from_front to the end of the list NLst.
  5. NLst.insert(0, from_back) — This line inserts the value stored in from_back at the beginning of the list NLst.
  6. NLst1 = [[21, 12], 31] — This line initializes NLst1 as a nested list.
  7. NLst3 = NLst1.copy() — This line creates a shallow copy of NLst1 and assigns it to NLst3.
  8. NLst2 = NLst1 — This line assigns the reference of NLst1 to NLst2, meaning both NLst1 and NLst2 point to the same list object.
  9. NLst2[-1] = 5 — This line modifies the last element of NLst2 to 5. Since NLst1 and NLst2 reference the same list object, this change also affects NLst1.
  10. NLst2.insert(1, 6) — This line inserts 6 at index 1 in NLst2. Again, since NLst1 and NLst2 reference the same list object, this change also affects NLst1.
  11. h_t(NLst1) — This line calls the function h_t with NLst1 as an argument.
  12. print(NLst1[0], NLst1[-1], len(NLst1)) — This line prints the first element, last element, and length of NLst1.
  13. print(NLst2[0], NLst2[-1], len(NLst2)) — This line prints the first element, last element, and length of NLst2.
  14. print(NLst3[0], NLst3[-1], len(NLst3)) — This line prints the first element, last element, and length of NLst3.

Answered By

2 Likes


Related Questions