Python Programming

Please leave a remark at the bottom of each page with your useful suggestion.


Table of Contents

  1. Python Introduction
  2. Python Startup
  3. Python Examples Program Collection 1
  4. Python Examples Program Collection 2
  5. Python Examples Program Collection 3
  6. Python Examples Program Collection 4
  7. Python Examples Program Collection 5
  8. Python Examples Program Collection 6
  9. Python Examples Program Collection 7
  10. Python Examples Program Collection 8

Python isinstance()

numbers = [1, 2, 3, 4, 2, 5]
# check if numbers is instance of list result = isinstance(numbers, list)
print(result) # Output: True

Python isinstance()

Example 1: How isinstance() works?

class Foo:
  a = 5
  
fooInstance = Foo()
print(isinstance(fooInstance, Foo))
print(isinstance(fooInstance, (list, tuple))) print(isinstance(fooInstance, (list, tuple, Foo)))

Python isinstance()

Example 2: Working of isinstance() with Native Types

numbers = [1, 2, 3]
result = isinstance(numbers, list)
print(numbers,'instance of list?', result) result = isinstance(numbers, dict) print(numbers,'instance of dict?', result) result = isinstance(numbers, (dict, list)) print(numbers,'instance of dict or list?', result) number = 5
result = isinstance(number, list)
print(number,'instance of list?', result) result = isinstance(number, int) print(number,'instance of int?', result)

Python String islower()

Example 1: Return Value from islower()

s = 'this is good'
print(s.islower())
s = 'th!s is a1so g00d'
print(s.islower())
s = 'this is Not good'
print(s.islower())

Python String islower()

Example 2: How to use islower() in a program?

s = 'this is good'
if s.islower() == True:
  print('Does not contain uppercase letter.')
else:
  print('Contains uppercase letter.')
  
s = 'this is Good'
if s.islower() == True:
  print('Does not contain uppercase letter.')
else:
  print('Contains uppercase letter.')

Python String isnumeric()

pin = "523"
# checks if every character of pin is numeric print(pin.isnumeric())
# Output: True

Python String isnumeric()

Example 1: Python isnumeric()

symbol_number = "012345"
# returns True as symbol_number has all numeric characters print(string1.isnumeric())
text = "Python3"
# returns False as every character of text is not numeric print(string2.isnumeric())

Python String isprintable()

text = 'apple'
# returns True if text is printable result = text.isprintable()
print(result) # Output: True

Python String isprintable()

Example 1: Python String isprintable()

text1 = 'python programming'
# checks if text1 is printable result1 = text1.isprintable()
print(result1) text2 = 'python programming\n'
# checks if text2 is printable result2 = text2.isprintable()
print(result2)

Python String isprintable()

Example 3: isprintable() with String Containing ASCII

# defining string using ASCII value 
text = chr(27) + chr(97)
# checks if text is printable if text.isprintable():
print('Printable') else: print('Not Printable')

Python String isspace()

Example 1: Working of isspace()

s = '   \t'
print(s.isspace())
s = ' a '
print(s.isspace())
s = ''
print(s.isspace())

Python String isspace()

Example 2: How to use isspace()?

s = '\t  \n'
if s.isspace() == True:
  print('All whitespace characters')
else:
  print('Contains non-whitespace characters')
  
s = '2+2 = 4'
if s.isspace() == True:
  print('All whitespace characters')
else:
  print('Contains non-whitespace characters.')

Python issubclass()

Example: How issubclass() works?

class Polygon:
  def __init__(polygonType):
    print('Polygon is a ', polygonType)
class Triangle(Polygon):
  def __init__(self):
    Polygon.__init__('triangle')
    
print(issubclass(Triangle, Polygon))
print(issubclass(Triangle, list))
print(issubclass(Triangle, (list, Polygon)))
print(issubclass(Polygon, (list, Polygon)))

Python Set issubset()

A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
# all items of A are present in B print(A.issubset(B))
# Output: True

Python Set issubset()

Example: Python Set issubset()

A = {'a', 'c', 'e'}
B = {'a', 'b', 'c', 'd', 'e'}
print('A is subset of B:', A.issubset(B))
print('B is subset of A:', B.issubset(A))

Python Set issuperset()

Example: How issuperset() works?

A = {1, 2, 3, 4, 5}
B = {1, 2, 3}
C = {1, 2, 3}
# Returns True
print(A.issuperset(B))
# Returns False
print(B.issuperset(A))
# Returns True
print(C.issuperset(B))

Python String istitle()

Example 1: Working of istitle()

s = 'Python Is Good.'
print(s.istitle())
s = 'Python is good'
print(s.istitle())
s = 'This Is @ Symbol.'
print(s.istitle())
s = '99 Is A Number'
print(s.istitle())
s = 'PYTHON'
print(s.istitle())

Python String istitle()

Example 2: How to use istitle()?

s = 'I Love Python.'
if s.istitle() == True:
  print('Titlecased String')
else:
  print('Not a Titlecased String')
  
s = 'PYthon'
if s.istitle() == True:
  print('Titlecased String')
else:
  print('Not a Titlecased String')

Python String isupper()

Example 1: Return value of isupper()

# example string
string = "THIS IS GOOD!"
print(string.isupper());
# numbers in place of alphabets
string = "THIS IS ALSO G00D!"
print(string.isupper());
# lowercase string
string = "THIS IS not GOOD!"
print(string.isupper());

Python String isupper()

Example 2: How to use isupper() in a program?

string = 'THIS IS GOOD'
if string.isupper() == True:
  print('Does not contain lowercase letter.')
else:
  print('Contains lowercase letter.')
  
string = 'THIS IS gOOD'
if string.isupper() == True:
  print('Does not contain lowercase letter.')
else:
  print('Contains lowercase letter.')

Python Dictionary items()

marks = {'Physics':67, 'Maths':87}
print(marks.items())
# Output: dict_items([('Physics', 67), ('Maths', 87)])

Python Dictionary items()

Example 1: Get all items of a dictionary with items()

# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sales.items())

Python Dictionary items()

Example 2: How items() works when a dictionary is modified?

# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
items = sales.items()
print('Original items:', items) # delete an item from dictionary
del[sales['apple']]
print('Updated items:', items)

Python iter()

# list of vowels
phones = ['apple', 'samsung', 'oneplus']
phones_iter = iter(phones)
print(next(phones_iter))   
print(next(phones_iter))    
print(next(phones_iter))    
# Output:
# apple
# samsung
# oneplus

Python iter()

Example 1: Python iter()

# list of vowels
vowels = ["a", "e", "i", "o", "u"]
# iter() with a list of vowels vowels_iter = iter(vowels)
print(next(vowels_iter)) print(next(vowels_iter)) print(next(vowels_iter)) print(next(vowels_iter)) print(next(vowels_iter))

Python iter()

Example 2: iter() for custom objects

class PrintNumber:
    def __init__(self, max):
        self.max = max
# iter() method in a class def __iter__(self): self.num = 0
return self
# next() method in a class def __next__(self): if(self.num >= self.max): raise StopIteration
self.num += 1 return self.num print_num = PrintNumber(3) print_num_iter = iter(print_num) print(next(print_num_iter)) # 1 print(next(print_num_iter)) # 2 print(next(print_num_iter)) # 3
# raises StopIteration print(next(print_num_iter))

Python iter()

Example 3: iter() with Sentinel Parameter

class DoubleIt:
    def __init__(self):
        self.start = 1
    def __iter__(self):
        return self
    def __next__(self):
        self.start *= 2
        return self.start
    __call__ = __next__
    
my_iter = iter(DoubleIt(), 16)
for x in my_iter:
    print(x)

Python String join()

text = ['Python', 'is', 'a', 'fun', 'programming', 'language']
# join elements of text with space print(' '.join(text))
# Output: Python is a fun programming language

Python String join()

Example 1: Working of the join() method

# .join() with lists
numList = ['1', '2', '3', '4']
separator = ', '
print(separator.join(numList))
# .join() with tuples numTuple = ('1', '2', '3', '4')
print(separator.join(numTuple))
s1 = 'abc' s2 = '123' # each element of s2 is separated by s1 # '1'+ 'abc'+ '2'+ 'abc'+ '3'
print('s1.join(s2):', s1.join(s2))
# each element of s1 is separated by s2 # 'a'+ '123'+ 'b'+ '123'+ 'b'
print('s2.join(s1):', s2.join(s1))

Python String join()

Example 2: The join() method with sets

# .join() with sets
test = {'2', '1', '3'}
s = ', '
print(s.join(test))
test = {'Python', 'Java', 'Ruby'} s = '->->'
print(s.join(test))

Python String join()

Example 3: The join() method with dictionaries

# .join() with dictionaries
test = {'mat': 1, 'that': 2}
s = '->'
# joins the keys only
print(s.join(test))
test = {1: 'mat', 2: 'that'} s = ', ' # this gives error since key isn't string
print(s.join(test))

Python Dictionary keys()

numbers = {1: 'one', 2: 'two', 3: 'three'}
# extracts the keys of the dictionary dictionaryKeys = numbers.keys()
print(dictionaryKeys) # Output: dict_keys([1, 2, 3])

Python Dictionary keys()

Example 1: Python Dictionary Keys()

employee = {'name': 'Phill', 'age': 22, 'salary': 3500.0}
# extracts the keys of the dictionary dictionaryKeys = employee.keys()
print(dictionaryKeys)

Python Dictionary keys()

Example 2: Update in dictionary updates the view object

employee = {'name': 'Phill', 'age': 22}
# extracts the dictionary keys
dictionaryKeys = employee.keys()
print('Before dictionary update:', dictionaryKeys)
# adds an element to the dictionary employee.update({'salary': 3500.0})
# prints the updated view object print('After dictionary update:', dictionaryKeys)

Python len()

languages = ['Python', 'Java', 'JavaScript']
# compute the length of languages length = len(languages)
print(length) # Output: 3

Python len()

Example 1: How len() works with tuples, lists and range?

testList = []
print(testList, 'length is', len(testList))
testList = [1, 2, 3] print(testList, 'length is', len(testList)) testTuple = (1, 2, 3)
print(testTuple, 'length is', len(testTuple))
testRange = range(1, 10) print('Length of', testRange, 'is', len(testRange))

Python len()

Example 2: How len() works with strings and bytes?

testString = ''
print('Length of', testString, 'is', len(testString))
testString = 'Python'
print('Length of', testString, 'is', len(testString))
# byte object testByte = b'Python' print('Length of', testByte, 'is', len(testByte)) testList = [1, 2, 3] # converting to bytes object testByte = bytes(testList)
print('Length of', testByte, 'is', len(testByte))

Python len()

Example 3: How len() works with dictionaries and sets?

testSet = {1, 2, 3}
print(testSet, 'length is', len(testSet))
# Empty Set testSet = set() print(testSet, 'length is', len(testSet)) testDict = {1: 'one', 2: 'two'}
print(testDict, 'length is', len(testDict))
testDict = {} print(testDict, 'length is', len(testDict)) testSet = {1, 2} # frozenSet frozenTestSet = frozenset(testSet)
print(frozenTestSet, 'length is', len(frozenTestSet))

Python len()

Example 4: How len() works for custom objects?

class Session:
    def __init__(self, number = 0):
      self.number = number
    
    def __len__(self):
      return self.number
# default length is 0
s1 = Session()
print(len(s1))
# giving custom length s2 = Session(6)
print(len(s2))

Python String ljust()

Example 1: Left justify string of minimum width

# example string
string = 'cat'
width = 5
# print left justified string
print(string.ljust(width))

Python String ljust()

Example 2: Left justify string and fill the remaining spaces

# example string
string = 'cat'
width = 5
fillchar = '*'
# print left justified string
print(string.ljust(width, fillchar))

Python locals()

print(locals())

Python locals()

Example 1: Python locals()

class local:
    l = 50
# locals inside a class print('\nlocals() value inside class\n', locals())

Python locals()

Example 2: locals() to change values

def localsPresent():
    present = True
    print(present)
    locals()['present'] = False;
    print(present)
localsPresent()

Python String lower()

message = 'PYTHON IS FUN'
# convert message to lowercase print(message.lower())
# Output: python is fun

Python String lower()

Example 1: Convert a string to lowercase

# example string
string = "THIS SHOULD BE LOWERCASE!"
print(string.lower())
# string with numbers # all alphabets should be lowercase string = "Th!s Sh0uLd B3 L0w3rCas3!"
print(string.lower())

Python String lower()

Example 2: How lower() is used in a program?

# first string
firstString = "PYTHON IS AWESOME!"
# second string
secondString = "PyThOn Is AwEsOmE!"
if(firstString.lower() == secondString.lower()):
print("The strings are same.") else: print("The strings are not same.")

Python String lstrip()

Example: Working of lstrip()

random_string = '   this is good '
# Leading whitepsace are removed
print(random_string.lstrip())
# Argument doesn't contain space
# No characters are removed.
print(random_string.lstrip('sti'))
print(random_string.lstrip('s ti'))
website = 'https://www.programiz.com/'
print(website.lstrip('htps:/.'))

Python String maketrans()

Example 1: Translation table using a dictionary with maketrans()

# example dictionary
dict = {"a": "123", "b": "456", "c": "789"}
string = "abc"
print(string.maketrans(dict))
# example dictionary
dict = {97: "123", 98: "456", 99: "789"}
string = "abc"
print(string.maketrans(dict))

Python String maketrans()

Example 2: Translation table using two strings with maketrans()

# first string
firstString = "abc"
secondString = "def"
string = "abc"
print(string.maketrans(firstString, secondString))
# example dictionary
firstString = "abc"
secondString = "defghi"
string = "abc"
print(string.maketrans(firstString, secondString))

Python String maketrans()

Example 3: Translational table with removable string with maketrans()

# first string
firstString = "abc"
secondString = "def"
thirdString = "abd"
string = "abc"
print(string.maketrans(firstString, secondString, thirdString))

Python map()

numbers = [2, 4, 6, 8, 10]
# returns square of a number
def square(number):
  return number * number
# apply square() function to each item of the numbers list squared_numbers_iterator = map(square, numbers)
# converting to list squared_numbers = list(squared_numbers_iterator) print(squared_numbers) # Output: [4, 16, 36, 64, 100]

Python map()

Example 1: Working of map()

def calculateSquare(n):
    return n*n
numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result) # converting map object to set numbersSquare = set(result) print(numbersSquare)

Python map()

Example 2: How to use lambda function with map()?

numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)
print(result) # converting map object to set numbersSquare = set(result) print(numbersSquare)

Python max()

numbers = [9, 34, 11, -4, 27]
# find the maximum number max_number = max(numbers)
print(max_number) # Output: 34

Python max()

Example 1: Get the largest item in a list

number = [3, 2, 8, 5, 10, 6]
largest_number = max(number);
print("The largest number is:", largest_number)

Python max()

Example 2: the largest string in a list

languages = ["Python", "C Programming", "Java", "JavaScript"]
largest_string = max(languages);
print("The largest string is:", largest_string)

Python max()

Example 3: max() in dictionaries

square = {2: 4, -3: 9, -1: 1, -2: 4}
# the largest key
key1 = max(square)
print("The largest key:", key1) # 2 # the key whose value is the largest
key2 = max(square, key = lambda k: square[k])
print("The key with the largest value:", key2) # -3 # getting the largest value print("The largest value:", square[key2]) # 9

Python max()

Example 4: Find the maximum among the given numbers

# find max among the arguments result = max(4, -5, 23, 5)
print("The maximum number is:", result)

Python memoryview()

Example 1: How memoryview() works in Python?

#random bytearray
random_byte_array = bytearray('ABC', 'utf-8')
mv = memoryview(random_byte_array)
# access memory view's zeroth index
print(mv[0])
# create byte from memory view
print(bytes(mv[0:2]))
# create list from memory view
print(list(mv[0:3]))

Python memoryview()

Example 2: Modify internal data using memory view

# random bytearray
random_byte_array = bytearray('ABC', 'utf-8')
print('Before updation:', random_byte_array)
mv = memoryview(random_byte_array)
# update 1st index of mv to Z
mv[1] = 90
print('After updation:', random_byte_array)

Python min()

numbers = [9, 34, 11, -4, 27]
# find the smallest number min_number = min(numbers)
print(min_number) # Output: -4

Python min()

Example 1: Get the smallest item in a list

number = [3, 2, 8, 5, 10, 6]
smallest_number = min(number);
print("The smallest number is:", smallest_number)

Python min()

Example 2: The smallest string in a list

languages = ["Python", "C Programming", "Java", "JavaScript"]
smallest_string = min(languages);
print("The smallest string is:", smallest_string)

Python min()

Example 3: min() in dictionaries

square = {2: 4, 3: 9, -1: 1, -2: 4}
# the smallest key
key1 = min(square)
print("The smallest key:", key1) # -2 # the key whose value is the smallest
key2 = min(square, key = lambda k: square[k])
print("The key with the smallest value:", key2) # -1 # getting the smallest value print("The smallest value:", square[key2]) # 1

Python min()

Example 4: Find the minimum among the given numbers

result = min(4, -5, 23, 5)
print("The minimum number is:", result)

Python next()

marks = [65, 71, 68, 74, 61]
# convert list to iterator
iterator_marks = iter(marks)
# the next element is the first element marks_1 = next(iterator_marks)
print(marks_1)
# find the next element which is the second element marks_2 = next(iterator_marks)
print(marks_2) # Output: 65 # 71

Python next()

Example 1: Get the next item

random = [5, 9, 'cat']
# converting the list to an iterator
random_iterator = iter(random)
print(random_iterator)
# Output: 5
print(next(random_iterator))
# Output: 9
print(next(random_iterator))
# Output: 'cat'
print(next(random_iterator))
# This will raise Error # iterator is exhausted
print(next(random_iterator))

Python next()

Example 2: Passing default value to next()

random = [5, 9]
# converting the list to an iterator
random_iterator = iter(random)
# Output: 5
print(next(random_iterator, '-1'))
# Output: 9 print(next(random_iterator, '-1')) # random_iterator is exhausted # Output: '-1'
print(next(random_iterator, '-1'))
print(next(random_iterator, '-1')) print(next(random_iterator, '-1'))

Python object()

Example: How object() works?

test = object()
print(type(test))
print(dir(test))

Python oct()

Example 1: How oct() works in Python?

# decimal to octal
print('oct(10) is:', oct(10))
# binary to octal
print('oct(0b101) is:', oct(0b101))
# hexadecimal to octal
print('oct(0XA) is:', oct(0XA))

Python oct()

Example 2: oct() for custom objects

class Person:
    age = 23
    def __index__(self):
        return self.age
    def __int__(self):
        return self.age
person = Person()
print('The oct is:', oct(person))

Python open()

Example 1: How to open a file in Python?

# opens test.text file of the current directory
f = open("test.txt")
# specifying the full path
f = open("C:/Python33/README.txt")

Python open()

Example 2: Providing mode to open()

# opens the file in reading mode
f = open("path_to_file", mode='r')
# opens the file in writing mode 
f = open("path_to_file", mode = 'w')
# opens for writing to the end 
f = open("path_to_file", mode = 'a')

Python ord()

character = 'P'
# find unicode of P unicode_char = ord(character)
print(unicode_char) # Output: 80

Python ord()

Example: How ord() works in Python?

print(ord('5'))    # 53
print(ord('A')) # 65
print(ord('$')) # 36

Python String partition()

Example: How partition() works?

string = "Python is fun"
# 'is' separator is found
print(string.partition('is '))
# 'not' separator is not found
print(string.partition('not '))
string = "Python is fun, isn't it"
# splits at first occurence of 'is'
print(string.partition('is'))

Python Set pop()

A = {'a', 'b', 'c', 'd'}
removed_item = A.pop()
print(removed_item)
# Output: c

Python Set pop()

Example 1: Python Set pop()

A = {'10', 'Ten', '100', 'Hundred'}
# removes random item of set A print('Pop() removes:', A.pop()) # updates A to new set without the popped item print('Updated set A:', A)

Python Set pop()

Example 2: pop() with an Empty Set

# empty set
A ={}
# throws an error print(A.pop())

Python Dictionary popitem()

Example: Working of popitem() method

person = {'name': 'Phill', 'age': 22, 'salary': 3500.0}
# ('salary', 3500.0) is inserted at the last, so it is removed.
result = person.popitem()
print('Return Value = ', result)
print('person = ', person)
# inserting a new element pair
person['profession'] = 'Plumber'
# now ('profession', 'Plumber') is the latest element
result = person.popitem()
print('Return Value = ', result)
print('person = ', person)

Python pow()

# compute 3^4 print(pow(3, 4));
# Output: 81

Python pow()

Example 1: Python pow()

# returns 2^2
print(pow(2, 2))  
# returns -2^2
print(pow(-2, 2))    
# returns 1/2^2 
print(pow(2, -2))   
 
# returns -1/-2^2 
print(pow(-2, -2))

Python pow()

Example 2: pow() with Modulus

x = 7
y = 2
z = 5
# compute x^y % z print(pow(x, y, z))

Python print()

message = 'Python is fun'
# print the string message print(message)
# Output: Python is fun

Python print()

Example 1: How print() works in Python?

print("Python is fun.")
a = 5
# Two objects are passed
print("a =", a)
b = a # Three objects are passed
print('a =', a, '= b')

Python print()

Example 2: print() with separator and end parameters

a = 5
print("a =", a, sep='00000', end='\n\n\n')
print("a =", a, sep='0', end='')

Python property()

Example 1: Create attribute with getter, setter, and deleter

class Person:
    def __init__(self, name):
        self._name = name
    def get_name(self):
        print('Getting name')
        return self._name
    def set_name(self, value):
        print('Setting name to ' + value)
        self._name = value
    def del_name(self):
        print('Deleting name')
        del self._name
    # Set property to use get_name, set_name
    # and del_name methods
    name = property(get_name, set_name, del_name, 'Name property')
p = Person('Adam')
print(p.name)
p.name = 'John'
del p.name

Python range()

# create a sequence of numbers from 0 to 3
numbers = range(4)
# iterating through the sequence of numbers
for i in numbers:
    print(i)
# Output:
# 0
# 1
# 2
# 3

Python Set remove()

languages = {'Python', 'Java', 'English'}
# remove English from the set languages.remove('English')
print(languages) # Output: {'Python', 'Java'}

Python Set remove()

Example 1: Remove an Element From The Set

# language set
language = {'English', 'French', 'German'}
# removing 'German' from language language.remove('German')
# Updated language set print('Updated language set:', language)

Python Set remove()

Example 2: Deleting Element That Doesn't Exist

# animal set
animal = {'cat', 'dog', 'rabbit', 'guinea pig'}
# Deleting 'fish' element animal.remove('fish')
# Updated animal print('Updated animal set:', animal)

Python String replace()

text = 'bat ball'
# replace b with c replaced_text = text.replace('b', 'c')
print(replaced_text) # Output: cat call

Python String replace()

Example 1: Using replace()

song = 'cold, cold heart'
# replacing 'cold' with 'hurt' print(song.replace('cold', 'hurt'))
song = 'Let it be, let it be, let it be, let it be'
# replacing only two occurences of 'let' print(song.replace('let', "don't let", 2))

Python String replace()

More Examples on String replace()

song = 'cold, cold heart'
replaced_song = song.replace('o', 'e')
# The original string is unchanged print('Original string:', song) print('Replaced string:', replaced_song) song = 'let it be, let it be, let it be' # maximum of 0 substring is replaced # returns copy of the original string
print(song.replace('let', 'so', 0))

Python repr()

numbers = [1, 2, 3, 4, 5]
# create a printable representation of the list printable_numbers = repr(numbers)
print(printable_numbers) # Output: [1, 2, 3, 4, 5]

Python repr()

Example 1: How repr() works in Python?

var = 'foo'
print(repr(var))

Python List reverse()

# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]
# reverse the order of list elements prime_numbers.reverse()
print('Reversed List:', prime_numbers) # Output: Reversed List: [7, 5, 3, 2]

Python List reverse()

Example 1: Reverse a List

# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)
# List Reverse systems.reverse()
# updated list print('Updated List:', systems)

Python List reverse()

Example 2: Reverse a List Using Slicing Operator

# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)
# Reversing a list	
# Syntax: reversed_list = systems[start:stop:step] reversed_list = systems[::-1]
# updated list print('Updated List:', reversed_list)

Python reversed()

seq_string = 'Python'
# reverse of a string print(list(reversed(seq_string)))
# Output: ['n', 'o', 'h', 't', 'y', 'P']

Python reversed()

Example 1: Python reversed() with Built-In Sequence Objects

seq_tuple = ('P', 'y', 't', 'h', 'o', 'n')
# reverse of a tuple object print(list(reversed(seq_tuple)))
seq_range = range(5, 9)
# reverse of a range print(list(reversed(seq_range)))
seq_list = [1, 2, 4, 3, 5]
# reverse of a list print(list(reversed(seq_list)))

Python reversed()

Example 2: reversed() with Custom Objects

class Vowels:
    vowels = ['a', 'e', 'i', 'o', 'u']
    def __reversed__(self):
        return reversed(self.vowels)
v = Vowels()
# reverse a custom object v print(list(reversed(v)))



Write Your Comments or Suggestion...