Posts

Showing posts from June, 2023

Python map() Built in Function

The map() function in Python executes a specified function for each item in an iterable. The item is sent to the function as a parameter. The map() function returns a map object, which is an iterator that yields the results of applying the function to each item. The map object can be converted into a list, tuple, set, or other collection type. Here are some examples of using map() function in Python: Using map() with a single iterable # This example applies the len() function to each element of a list and returns a list of lengths words = ["apple", "banana", "cherry"] lengths = list(map(len, words)) print(lengths) # Output: [5, 6, 6] Using map() with multiple iterables # This example applies the pow() function to two lists of numbers and returns a list of powers base = [2, 3, 4] exponent = [1, 2, 3] powers = list(map(pow, base, exponent)) print(powers) # Output: [2, 9, 64] Using map() with lambda functions # This example uses a lambda function to squ...

Python max() Built in Function

The max() function in Python returns the item with the highest value, or the item with the highest value in an iterable. An iterable can be a list, tuple, set, dictionary, string, etc. The max() function can also take two or more arguments and return the largest one. Here are some examples of using max() function in Python: Using max() with a single iterable # This example returns the largest number in a list numbers = [18 ,52 ,23 ,41 ,32] largest = max(numbers) print(largest) # Output: 52 Using max() with multiple arguments # This example returns the largest number among four arguments result = max(5 ,10 ,25 ,99) print(result) # Output: 99 Using max() with strings # This example returns the alphabetically last string in a list words = ["apple" ,"banana" ,"cherry" ,"date"] last = max(words) print(last) # Output: date Using max() with a key function # This example returns the longest string in a list using len() as a key function words = [...

Python memoryview() Built in Function

The memoryview() function in Python returns a memory view object of a given argument. A memory view object allows you to access the internal data of an object that supports the buffer protocol without copying it. The buffer protocol provides a way to access the low-level memory of an object. Examples of objects that support the buffer protocol are bytes, bytearray, array.array, etc. Here are some examples of using memoryview() function in Python: Using memoryview() with a bytearray # This example creates a memory view object from a bytearray and prints its elements byte_array = bytearray('ABC', 'utf-8') mv = memoryview(byte_array) print(mv[0]) # Output: 65 print(bytes(mv[0:2])) # Output: b'AB' print(list(mv[0:3])) # Output: [65 ,66 ,67] Using memoryview() to modify internal data # This example modifies the first element of a bytearray using a memory view object byte_array = bytearray('ABC', 'utf-8') print('Before update:', byte_ar...

Python min() Built in Function

The min() function in Python returns the smallest item in an iterable or the smallest item among two or more arguments. An iterable can be a list, tuple, set, dictionary, string, etc. The min() function can also take a key function to customize the comparison criteria. Here are some examples of using min() function in Python: Using min() with a single iterable # This example returns the smallest number in a list numbers = [9 ,34 ,11 ,-4 ,27] smallest = min(numbers) print(smallest) # Output: -4 Using min() with multiple arguments # This example returns the smallest number among four arguments result = min(5 ,10 ,25 ,99) print(result) # Output: 5 Using min() with strings # This example returns the alphabetically first string in a list words = ["apple" ,"banana" ,"cherry" ,"date"] first = min(words) print(first) # Output: apple Using min() with a key function # This example returns the shortest string in a list using len() as a key function w...

Python next() Built in Function

The next() function in Python returns the next item from an iterator. An iterator is an object that can be iterated over, such as a list, tuple, string, etc. The next() function can also take a default value as a second argument, which is returned if the iterator has no more items. Here are some examples of using next() function in Python: Using next() with a list iterator # This example creates an iterator from a list and prints its items one by one mylist = iter(["apple" ,"banana" ,"cherry"]) x = next(mylist) print(x) # Output: apple x = next(mylist) print(x) # Output: banana x = next(mylist) print(x) # Output: cherry Using next() with a default value # This example returns a default value when the iterator has reached its end mylist = iter(["apple" ,"banana" ,"cherry"]) while True:     item = next(mylist ,"end")     if item == "end":         break     print(item) # Output: apple banana cherry Us...

Python object() Built in Function

The object() function in Python returns a new featureless object that has no attributes. It is a base class for all other classes in Python. The object() function can also be used to test if an object is an instance of a class. Here are some examples of using object() function in Python: Using object() to create a featureless object # This example creates an object using object() and tries to access its attributes obj = object() print(obj) # Output: <object object at 0x000001F8C9A6E0D0> print(obj.name) # Output: AttributeError: 'object' object has no attribute 'name' Using object() as a base class # This example creates a class that inherits from object and adds some attributes class Bike(object):     def __init__(self ,name ,gear):         self.name = name         self.gear = gear     def __str__(self):         return f"{self.name} has {se...

Python oct() Built in Function

The oct() function in Python converts an integer number into an octal string. Octal strings in Python are prefixed with 0o. The oct() function can also convert numbers from other bases, such as binary or hexadecimal, into octal. Here are some examples of using oct() function in Python: Using oct() with a decimal number # This example converts a decimal number into an octal string x = oct(12) print(x) # Output: 0o14 Using oct() with a binary number # This example converts a binary number into an octal string x = oct(0b1010) print(x) # Output: 0o12 Using oct() with a hexadecimal number # This example converts a hexadecimal number into an octal string x = oct(0xAF) print(x) # Output: 0o257 If you have any questions about this code, you can drop a line in comment .

Python open() Built in Function

The open() function is used to open a file and return a file object that can be used to read or write data. The syntax of the open() function is: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) The file parameter is the name of the file or a path to it. The mode parameter specifies how the file should be opened. There are different modes for reading, writing and appending data. Some common modes are: “r” - Read - Default value. Opens a file for reading, error if the file does not exist “w” - Write - Opens a file for writing, creates the file if it does not exist “a” - Append - Opens a file for appending, creates the file if it does not exist “r+” - Read/Write - Opens a file for both reading and writing, error if the file does not exist Here are some examples of using the open() function in Python: To open a text file named “demofile.txt” in read mode and print its content: f = open("demofile.txt", "r...

Python ord() Built in Function

The ord() function is used to get the integer value that represents the Unicode code point of a character. The syntax of the ord() function is: ord(char) The char parameter is a string of length one that contains a Unicode character. The return value is an integer between 0 and 1114111 (inclusive). Some common Unicode code points are: 48 for ‘0’ 65 for ‘A’ 97 for ‘a’ 8364 for ‘€’ Here are some examples of using the ord() function in Python: To get the Unicode code point of an integer character: print(ord('8')) # prints 48 To get the Unicode code point of an alphabet character: print(ord('R')) # prints 82 To get the Unicode code point of a special character: print(ord('&')) # prints 38 To get the Unicode code point of a non-ASCII character: print(ord('€')) # prints 8364  If you have any questions about this code, you can drop a line in comment .

Python print() Built in Function

The print() function is used to display output to the standard output device (usually the screen). The syntax of the print() function is: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) The objects parameter is required and can be any number of objects that you want to print. The objects will be converted to strings before printing. The sep parameter is optional and specifies how to separate the objects if there are more than one. The default value is a single space ’ '. The end parameter is optional and specifies what to print at the end of the line. The default value is a newline character ‘\n’. The file parameter is optional and specifies an object with a write method where the output will be printed instead of sys.stdout (the standard output). The flush parameter is optional and specifies whether to forcibly flush the stream after printing. Here are some examples of using the print() function in Python: To print a simple message: print("H...

Python property() Built in Function

The property() function is used to create and return a property object that has a getter, a setter, and a deleter method. The syntax of this function is: property(fget=None, fset=None, fdel=None, doc=None) The fget parameter is optional and specifies a function to get the value of the attribute. The fset parameter is optional and specifies a function to set the value of the attribute. The fdel parameter is optional and specifies a function to delete the attribute. The doc parameter is optional and specifies a string that serves as the documentation for the attribute. The property() function can be used as a decorator or as a normal function. Here are some examples of using the property() function in Python: To create a read-only property using @property decorator: class Person:     def __init__(self, name):         self._name = name # private attribute     @property     def name(self): # getter method ...

Python range() Built in Function

The range() function is used to create and return a sequence of integer numbers as per the argument passed. The syntax of this function is: range(start, stop, step) The start parameter is optional and specifies the starting number of the sequence. The default value is 0. The stop parameter is required and specifies the end number of the sequence (exclusive). The step parameter is optional and specifies the increment or decrement of the sequence. The default value is 1. The range() function can be used with for loops to iterate over a sequence of numbers. It can also be used with list() function to create a list of numbers. Here are some examples of using the range() function in Python: To create a sequence of numbers from 0 to 5, and print each item in the sequence: x = range(6) for n in x:     print(n) # prints 0 1 2 3 4 5 To create a sequence of numbers from 10 to -10, with a step of -2, and print each item in the sequence: x = range(10, -11, -2) for n in x:  ...

Python repr() Built in Function

The repr() function is used to return a printable representation of the given object. The syntax of this function is: repr(object) The object parameter is required and specifies the object whose representation is needed. The repr() function returns a string that can be evaluated by eval() function to recreate the original object. The repr() function can be useful for debugging and logging purposes, as it shows more details about the object than str() function. It can also be used to customize the representation of user-defined classes by overriding the repr() method. Here are some examples of using the repr() function in Python: To get the representation of a built-in type such as list: x = [1, 2, 3] print(repr(x)) # prints '[1, 2, 3]' To get the representation of a custom class without overriding repr() method: class Student:     def __init__(self, name):         self.name = name s = Student("Alice") print(repr(s)) # prints '...

Python reversed() Built in Function

The reversed() function is used to return a reversed iterator object of a given sequence object. The syntax of this function is: reversed(sequence) The sequence parameter is required and specifies the sequence object (such as list, tuple, string, range) whose reverse order is needed. The reversed() function returns an iterator object that can be used with for loops or converted to a list using list() function. The reversed() function can be useful for reversing the order of elements in a sequence without modifying the original sequence. It can also be used with sorted() function to sort a sequence in descending order. Here are some examples of using the reversed() function in Python: To reverse the order of a string and print each character: s = "Python" r = reversed(s) for c in r:     print(c) # prints n o h t y P To reverse the order of a list and create a new list: l = [1, 2, 3, 4, 5] r = reversed(l) new_l = list(r) print(new_l) # prints [5, 4, 3, 2, 1] To sor...

Python round() Built in Function

The round() function in Python returns a floating-point number rounded to the specified number of decimals. The syntax is: round(number, ndigits) where number is the number to be rounded and ndigits is the number of decimal places to round to. If ndigits is omitted or None, then the number is rounded to the nearest integer. Here are some examples of using round() with different values of ndigits: # Round 13.46 to the nearest integer print(round(13.46)) # Output: 13 # Round 13.46 to one decimal place print(round(13.46, 1)) # Output: 13.5 # Round 1.5 up and 2.5 down print(round(1.5)) # Output: 2 print(round(2.5)) # Output: 2 # Round -1.25 to zero decimal places print(round(-1.25)) # Output: -1 If you have any questions about this code, you can drop a line in comment .

Python set() Built in Function

A set in Python is an unordered collection of unique items that supports various operations such as membership testing, union, intersection, difference and symmetric difference. The syntax for creating a set is: set(iterable) where iterable is any object that can be iterated over, such as a list, a tuple or a string. Alternatively, you can use curly braces {} to create a set with literal values. Here are some examples of creating sets with different iterables: # Create a set from a list my_set = set([1, 2, 3]) print(my_set) # Output: {1, 2, 3} # Create a set from a tuple my_set = set((4, 5, 6)) print(my_set) # Output: {4, 5, 6} # Create a set from a string my_set = set("hello") print(my_set) # Output: {'h', 'e', 'l', 'o'} # Create a set with literal values my_set = {7, 8 ,9} print(my_set) # Output: {7 ,8 ,9} If you have any questions about this code, you can drop a line in comment .

Python setattr() Built in Function

The setattr() function in Python sets the value of the specified attribute of the specified object. The syntax is: setattr(object, name, value) where object is any object that has attributes, name is a string that represents the name of an attribute and value is any value that can be assigned to an attribute. Here are some examples of using setattr() with different objects: # Create a class with two attributes class Person:     name = "John"     age = 36 # Create an instance of Person p = Person() # Use setattr() to change the value of name setattr(p, "name", "Jane") print(p.name) # Output: Jane # Use setattr() to create a new attribute called country setattr(p, "country", "Norway") print(p.country) # Output: Norway # Use setattr() to assign None to an existing attribute setattr(p, "age", None) print(p.age) # Output: None If you have any questions about this code, you can drop a line in comment .

Python slice() Built in Function

The slice() function in Python returns a slice object that can be used to slice any sequence (string, tuple, list, range or bytes). The syntax is: slice(start, stop, step) where start is the starting index of the slice (inclusive), stop is the ending index of the slice (exclusive) and step is the increment between each index. If any of these parameters are omitted, they default to None. Here are some examples of using slice() with different sequences: # Create a string my_string = "Python Programming" # Use slice() to get a substring sliced_string = slice(7) # equivalent to slice(None, 7, None) print(my_string[sliced_string]) # Output: Python # Use slice() with negative indices sliced_string = slice(-4, -1) # equivalent to slice(-4, -1, None) print(my_string[sliced_string]) # Output: ing # Use slice() with step parameter sliced_string = slice(0, 12 ,2) # equivalent to slice(None ,12 ,2) print(my_string[sliced_string]) # Output: Pto rg # Create a list my_list = [1 ,2 ,...

Python sorted() Built in Function

The sorted() function in Python returns a new sorted list from the items in an iterable. The syntax is: sorted(iterable, key=None, reverse=False) where iterable is any sequence or collection that supports iteration, key is a function that defines the sorting order and reverse is a boolean value that indicates whether to sort in ascending or descending order. If any of these parameters are omitted, they default to None and False respectively. Here are some examples of using sorted() with different iterables: # Create a list of numbers my_list = [6 ,9 ,3 ,1] # Use sorted() to get a new sorted list sorted_list = sorted(my_list) print(sorted_list) # Output: [1 ,3 ,6 ,9] # Use sorted() with reverse parameter sorted_list = sorted(my_list, reverse=True) print(sorted_list) # Output: [9 ,6 ,3 ,1] # Create a string my_string = "Python Programming" # Use sorted() to get a new sorted list of characters sorted_string = sorted(my_string) print(sorted_string) # Output: [' ', ...

Python staticmethod() Built in Function

The staticmethod() function in Python returns a static method for a given function. A static method is a method that does not require an instance of the class or the class itself as an argument. The syntax is: staticmethod(function) where function is any callable object that can be invoked without an object or a class. Here are some examples of using staticmethod() with different functions: # Define a function outside a class def hello(name):     print(f"Hello, {name}!") # Use staticmethod() to create a static method hello = staticmethod(hello) # Call the static method without an object or a class hello("Alice") # Output: Hello, Alice! # Define a class with a static method class Mathematics:     # Use @staticmethod decorator to declare a static method     @staticmethod     def addNumbers(x, y):         return x + y # Call the static method using the class name print(Mathematics.addNumbers(5...

Python str() Built in Function

The str() function in Python returns a string representation of an object. The syntax is: str(object, encoding=‘utf-8’, errors=‘strict’) where object is any Python object that can be converted to a string, encoding is the name of the encoding used to decode byte objects (default is ‘utf-8’), and errors is the type of error handling for decoding errors (default is ‘strict’). Here are some examples of using str() with different objects: # Use str() with numbers num = 42 print(str(num)) # Output: '42' # Use str() with booleans flag = True print(str(flag)) # Output: 'True' # Use str() with lists my_list = [1, 2, 3] print(str(my_list)) # Output: '[1, 2, 3]' # Use str() with byte objects my_bytes = b'Hello' print(str(my_bytes)) # Output: "b'Hello'" print(str(my_bytes, encoding='ascii')) # Output: 'Hello' If you have any questions about this code, you can drop a line in comment .

Python sum() Built in Function

The sum() function in Python is a built-in function that returns the sum of an iterable such as a list, tuple, set or dictionary. It can also take an optional start parameter that specifies the initial value to be added to the sum. Here are some examples of using the sum() function: # Example 1: Summing a list of numbers num = [3.5, 5, 2, -5] # start parameter is not provided numSum = sum(num) print(numSum) # Output: 5.5 # start = 15 numSum = sum(num, 15) print(numSum) # Output: 20.5 # Example 2: Summing two numbers using + a = 10 b = 20 c = a + b # same as sum([a,b]) print(c) # Output: 30 # Example 3: Summing values of a dictionary d = {'a':10, 'b':20, 'c':30} dSum = sum(d.values()) print(dSum) # Output: 60 # Note: sum(d.keys()) will raise an error as keys are not numbers If you have any questions about this code, you can drop a line in comment .

Python super() Built in Function

The super() function in Python is a built-in function that allows you to access the methods and properties of a parent class from a child class. It can also take optional arguments that specify the subclass and an instance of that subclass. Here are some examples of using the super() function: # Example 1: Calling parent constructor from child constructor class Vehicle:     def __init__(self):         print('Vehicle __init__() called') class Car(Vehicle):     def __init__(self):         super().__init__() # same as Vehicle.__init__(self)         print('Car __init__() called') car = Car() # Output: # Vehicle __init__() called # Car __init__() called # Example 2: Calling parent method from child method class Animal:     def sound(self):         print('Animal sound') class Dog(Animal):     ...

Python tuple() Built in Function

The tuple() function in Python is a built-in function that creates a tuple object from an iterable such as a list, set, string or dictionary. A tuple is a collection of data that is ordered and unchangeable. Here are some examples of using the tuple() function: # Example 1: Creating a tuple from a list my_list = [1, 2, 3] my_tuple = tuple(my_list) print(my_tuple) # Output: (1, 2, 3) # Example 2: Creating a tuple from a set my_set = {4, 5, 6} my_tuple = tuple(my_set) print(my_tuple) # Output: (4, 5, 6) # Example 3: Creating a tuple from a string my_string = "hello" my_tuple = tuple(my_string) print(my_tuple) # Output: ('h', 'e', 'l', 'l', 'o') # Example 4: Creating a tuple from a dictionary my_dict = {"a":10, "b":20} my_tuple = tuple(my_dict) # only keys are taken print(my_tuple) # Output: ('a', 'b') If you have any questions about this code, you can drop a line in comment .

Python type() Built in Function

The type() function in Python is a built-in function that returns the class type of an object or creates a new type object. Here are some examples of using the type() function: # Example 1: Getting the type of an object x = 10 # integer y = "hello" # string z = [1, 2, 3] # list print(type(x)) # Output: <class 'int'> print(type(y)) # Output: <class 'str'> print(type(z)) # Output: <class 'list'> # Example 2: Creating a new type object # syntax: type(name, bases, dict) MyClass = type("MyClass", (object,), {"a":10, "b":20}) # same as class MyClass(object): a = 10; b = 20 obj = MyClass() print(type(obj)) # Output: <class '__main__.MyClass'> print(obj.a) # Output: 10 print(obj.b) # Output: 20 If you have any questions about this code, you can drop a line in comment .

Python vars() Built in Function

The vars() function in Python is a built-in function that returns the dict attribute of an object. The dict attribute is a dictionary that contains all the attributes and values of an object. Here are some examples of using the vars() function: # Example 1: Getting the __dict__ attribute of a class object class Person:     name = "John"     age = 36     country = "Norway" x = vars(Person) print(x) # Output: {'name': 'John', 'age': 36, 'country': 'Norway'} # Example 2: Getting the __dict__ attribute of an instance object class Fruit:     def __init__(self, apple=5, banana=10):         self.apple = apple         self.banana = banana eat = Fruit() y = vars(eat) print(y) # Output: {'apple': 5, 'banana': 10} If you have any questions about this code, you can drop a line in comment .

Python zip() Built in Function

The zip() function in Python is a built-in function that returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc. Here are some examples of using the zip() function: # Example 1: Zipping two lists of equal length names = ['apple', 'banana', 'cherry'] count = [25, 31, 85] result = zip(names, count) for item in result:     print(item) # Output: ('apple', 25), ('banana', 31), ('cherry', 85) # Example 2: Zipping two lists of different length index = [1, 2, 3] languages = ['python', 'c', 'c++', 'java'] dictionary = dict(zip(index, languages)) print(dictionary) # Output: {1: 'python', 2: 'c', 3: 'c++'} If you have any questions about this code, you can drop a line in comment .

Python String center() Method

The Python center() method is a string method that returns a new string that is padded with a specified character (space by default) on both sides of the original string. The length of the new string is specified by a parameter. Here is an example of how to use the center() method to align a string with 20 characters and use # as the padding character: str = "Hello Javatpoint" str2 = str.center(20,'#') print("Old value:", str) print("New value:", str2) Output: Old value: Hello Javatpoint New value: ##Hello Javatpoint## If you have any questions about this code, you can drop a line in comment .

Python String casefold() Method

The casefold() method converts all characters of the string into lowercase letters and returns a new string. This method is similar to lower() , but it also performs more aggressive case conversions for some characters that do not have a direct lowercase equivalent. For example: text = "pYtHon" # convert all characters to lowercase lowercased_string = text.casefold() print(lowercased_string) # Output: python color1 = 'weiß' # German word for white color2 = 'weiss' print(color1 == color2) # False print(color1.lower() == color2.lower()) # False print(color1.casefold() == color2.casefold()) # True If you have any questions about this code, you can drop a line in comment .

Python String capitalize() Method

The capitalize() method converts the first character of a string to an uppercase letter and all other alphabets to lowercase. For example: sentence = "i love PYTHON" # converts first character to uppercase and others to lowercase capitalized_string = sentence.capitalize() print(capitalized_string) # Output: I love python If you have any questions about this code, you can drop a line in comment .