reversed()

reversed(my_sequence)
my_sequence : object supporting sequence protocol.
Returns the reversed iterator

Using a list

Details on list
my_list=['One','Two','Three']
print(my_list) # ['One', 'Two', 'Three']
my_list=list(reversed(my_list))
print(my_list) # ['Three', 'Two', 'One']

Using a tuple

Details on tuple
my_tuple=('One','Two','Three')
print(my_tuple) # ('One', 'Three', 'Two')
my_tuple=tuple(reversed(my_tuple))
print(my_tuple) # ('Three', 'Two', 'One')
Using a range
my_range=range (6)
for i in my_range:
  print(i, end=' ') # 0 1 2 3 4 5
my_range2=reversed(my_range)
for i in my_range2:
  print(i, end=' ') # 5 4 3 2 1 0
using a string
my_str='plus2net.com'
print(list(reversed(my_str)))
 # ['m', 'o', 'c', '.', 't', 'e', 'n', '2', 's', 'u', 'l', 'p']

reversing a string

Read more on join()
str='plus2net'
str_rev=''.join(reversed(str))
print(str_rev)
Output
ten2sulp

Example 1: Using reversed() on a Set

More on set
my_set = {1, 2, 3, 4}
reversed_set = list(reversed(list(my_set)))
print(reversed_set)  # Output: [4, 3, 2, 1]
Output:
[4, 3, 2, 1]

Example 2: Using reversed() with Enumerate

More on Enumerate
my_list = ['a', 'b', 'c', 'd']
for index, value in enumerate(reversed(my_list)):
    print(f'{index}: {value}')  
Output: Index with reversed values
0: d
1: c
2: b
3: a

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer