Python reversed() function

Filed Under: Python

Python reversed() function returns a reversed iterator from the specified sequence argument.

Python reversed()

Python reversed() function syntax is:


reversed(seq)
  • The input argument must be a sequence, for example tuple, list, string etc.
  • The returned object is of type reversed and it’s an iterator.
  • We can supply a custom object as reversed() function argument if it has __reversed__() method or supports the sequence protocol.
  • We need to implement __len__() method and the __getitem__() method with integer arguments starting at 0 to support sequence protocol.

reversed() with sequence

Let’s look at reversed() function examples with standard sequence objects such as string, bytes, tuple, list etc.


def print_iterator(it):
    for x in it:
        print(x, end=' ')
    print('\n')


# reversed string
r = reversed('abc')
print(type(r))
print(r)
print_iterator(r)

# reversed list
r = reversed([1, 2, 3])
print_iterator(r)

# reversed tuple
r = reversed((1, 2, 3))
print_iterator(r)

# reversed bytes
r = reversed(bytes('abc', 'utf-8'))
print_iterator(r)

# reversed bytearray
r = reversed(bytearray('abc', 'utf-8'))
print_iterator(r)

Output:


<class 'reversed'>
<reversed object at 0x109d1f208>
c b a 

3 2 1 

3 2 1 

99 98 97 

99 98 97 

Notice that bytes and bytearray elements are converted to integer while printing on console.

reversed() with object having __reversed__ method


# object with __reversed__ method
class Data:
    name = ''

    def __init__(self, n):
        self.name = n

    def __reversed__(self):
        return reversed(self.name)


d = Data('ABC')

r = reversed(d)

print_iterator(r)

Output: C B A

reversed() with object supporting sequence protocol


# object supporting sequence protocol i.e.
# implementing __len__() and __getitem__ method
class MyTupleWrapper:
    t = ()

    def __init__(self, tu):
        if not isinstance(tu, tuple):
            return ValueError('Only accepts tuple')
        self.t = tu

    def __len__(self):
        return len(self.t)

    def __getitem__(self, index):
        return self.t[index]


mt = MyTupleWrapper((1, 2, 3, 4))
r = reversed(mt)
print_iterator(r)

Output: 4 3 2 1

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

Comments

  1. POONAM says:

    hi

    I have one question if suppose I want to fetch the last two digit data only in one pdf file so how I can fetch.
    Please let me know it’s urgent and I am very new in python. i am giving input file but u cant see the file thats why i am mentioning my input text in pdf file . Here find my python code :

    import PyPDF2
    pdf_file = open(‘C:\Python27\\testing2.pdf’,’rb’)
    read_pdf = PyPDF2.PdfFileReader(pdf_file)
    page = read_pdf.getPage(0)
    page_content = page.extractText()
    for i in reversed(range(0, len(page_content))):
    if page_content[i] != ” “:
    print(page_content[i])
    break
    i += 1
    print (page_content)

    input is like :::: this is my file with page number 88
    the output I want :::: 88

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages