Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Reversing a String Using reversed()

00:00 In this lesson, you’ll learn how to reverse a string using the reversed() built-in function. reversed() is a built-in function which returns an iterator that yields sequence items in reverse order. In this context, an iterator refers to any object which implements the magic method .__next__().

00:17 While implementations of this method are left to the user, calls to it are generally expected to return the next item in a given sequence in some logical order. For example, let’s take a string and turn it into an iterator by using the built-in iter() function. If you do this for the string "Hello" and then call .__next__() repeatedly, you’ll get the characters in a sequential order.

00:41 Note that this only works for objects which implement the .__iter__() magic method, which strings do. You can retrieve the next item in the sequence repeatedly until you run out of characters.

00:59 The reversed() function does something quite similar but in reverse. When calling .__next__(), rather than getting the first element of the sequence, the last one is returned.

01:08 Subsequent calls iterate over this sequence in reverse order. Doing this repeatedly to a string iterable will yield all of the characters in reverse.

01:23 .join() is a method implemented for string objects in Python, which can take in any iterable and concatenate it using the string object as a separator. For example, if you pass the list of strings ["a", "b", "c"] to the method .join(), called from the string object comprised only of the character "+", you would get back the string 'a+b+c'.

01:44 If the string object is just a blank string, you would get the string 'abc'.

01:53 Recall that the string method takes in any iterable comprised of string objects and that the function reversed() returns an iterator that yields string objects when applied to a string. .join() can be called directly on the iterator returned by the function reversed() to reverse your string.

02:10 You can therefore use .join() and reversed() to reverse strings and python in a single line of code.

Become a Member to join the conversation.