How can you obtain a list of words in reverse order from the string 'Python is fun'? a) 'Python is fun'.split().reversed() b) reversed('Python is fun'.split()) c) 'Python is fun'.r... How can you obtain a list of words in reverse order from the string 'Python is fun'? a) 'Python is fun'.split().reversed() b) reversed('Python is fun'.split()) c) 'Python is fun'.reversed().split() d) 'Python is fun'.split().reverse()
Understand the Problem
The question is asking for the correct method to reverse the order of words in the given string 'Python is fun'. It presents multiple options, and we need to evaluate which one correctly achieves the task.
Answer
reversed('Python is fun'.split())
Use the code reversed('Python is fun'.split())
to obtain the list of words in reverse order. The correct choice is b)
.
Answer for screen readers
Use the code reversed('Python is fun'.split())
to obtain the list of words in reverse order. The correct choice is b)
.
More Information
Using reversed('Python is fun'.split())
first splits the string into words ['Python', 'is', 'fun'] and then reverses the order to ['fun', 'is', 'Python'].
Tips
A common mistake is to use reverse()
instead of reversed()
, or to chain reverse()
directly on split()
, both of which are incorrect.
Sources
- Python: Reverse Order Of Words - string - Stack Overflow - stackoverflow.com