ProgrammingModerateTCS NQT · Infosys

What is printed on the second line?

What is printed on the second line?
u = ''
for ch in 'abc':
    u = ch + u
print(u)
  1. A. abc
  2. B. bca
  3. C. cba
  4. D. cab

Correct answer: C. cba

Each new character is put in front of the old text, so the final string is built from the last character backwards. Prepending copies the whole string each time, so the loop is O(n squared) in total.

More Python Programming questions

Exams that ask this topic