PCEP-30-02 · Question #265
You want to print each name of the list on a new line. data = ['Peter', 'Paul', 'Mary', 'Jane'] Which statement will you use?
The correct answer is B. print('\n'.join(data)). Option B is correct because '\n'.join(data) is the standard Python idiom: the join() method belongs to strings, not lists, and takes an iterable as its argument - it inserts the string ('\n') between each element of data, producing Peter\nPaul\nMary\nJane. Why the others fail…
Question
data = ['Peter', 'Paul', 'Mary', 'Jane']
Which statement will you use?Options
- Aprint(data.concatenate('\n'))
- Bprint('\n'.join(data))
- Cprint(data.join('\n'))
- Dprint(data.join('%s\n', names))
How the community answered
(50 responses)- A6% (3)
- B78% (39)
- C4% (2)
- D12% (6)
Explanation
Option B is correct because '\n'.join(data) is the standard Python idiom: the join() method belongs to strings, not lists, and takes an iterable as its argument - it inserts the string ('\n') between each element of data, producing Peter\nPaul\nMary\nJane.
Why the others fail:
- A -
list.concatenate()doesn't exist in Python; lists have no such method. - C -
join()is a string method, not a list method;data.join(...)would raise anAttributeError. - D - Same problem as C (calling join on a list), plus
join()takes one argument (an iterable), not a format string and a variable.
Memory tip: Think of it as "the glue goes first." Whatever you want between items - ',', ' ', '\n' - is the string you call .join() on, and the list is passed into it. If you ever write list.join(separator), flip it around.
Community Discussion
No community discussion yet for this question.