Python

Python List sort() Method with Examples

In the previous article, we have discussed Python List reverse() Method with Examples
List in Python:

Lists in Python are mutable sequences. They are extremely similar to tuples, except they do not have immutability constraints. Lists are often used to store collections of homogeneous things, but there is nothing stopping you from storing collections of heterogeneous items as well.

List sort() Method in Python:

The sort() method sorts the elements of a list in ascending or descending order.

By default, the sort() method ascends the list.

Syntax:

list.sort(key=...., reverse=....)

Alternatively, you can use Python’s built-in sorted() function to accomplish the same thing.

sorted(list, key=...., reverse=....)

Note: The most basic distinction between sort() and sorted() is that sort() changes the list directly and returns no value, whereas sorted() does not change the list and returns the sorted list.

Parameter Values of sort():

Sort() does not require any additional parameters by default. It does, however, have two optional parameters:

  • reverse: This is Optional. The list will be sorted descending if reverse=True is set. The default value is reverse=False.
  • key: This is Optional. A function that allows you to specify the sorting criteria (s)

Return Value:

The sort() method produces no output. Instead, it modifies the original list.

Use sorted if you want a function to return the sorted list rather than change the original list ().

Examples:

Example1:

Input:

Given List = ['g', 'r', 'c', 'x', 'e']

Output:

The Given original list is : ['g', 'r', 'c', 'x', 'e']
The given list after sorting in ascending order:  ['c', 'e', 'g', 'r', 'x']

Example2:

Input:

Given List = ['hello', 'this', 'is', 'btechgeeks']

Output:

The Given original list is : ['hello', 'this', 'is', 'btechgeeks']
The given list after sorting in descending order: 
['this', 'is', 'hello', 'btechgeeks']

List sort() Method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

1) sort in Ascending Order

Approach:

  • Give the list as static input and store it in a variable.
  • Print the given original list.
  • Apply sort() function to the given list to sort the given list elements in ascending order.
  • Print the list after sorting all its elements in ascending order.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ['g', 'r', 'c', 'x', 'e']
# Print the given original list.
print("The Given original list is :", gvn_lst)
# Apply sort() function to the given list to sort the given list elements in
# ascending order.
gvn_lst.sort()
# Print the list after sorting all its elements in ascending order.
print("The given list after sorting in ascending order: ", gvn_lst)

Output:

The Given original list is : ['g', 'r', 'c', 'x', 'e']
The given list after sorting in ascending order:  ['c', 'e', 'g', 'r', 'x']
2) sort in Descending Order

Approach:

  • Give the list as static input and store it in a variable.
  • Print the given original list.
  • Apply sort() function to the given list by passing the argument as reverse = “True” to sort the given list elements in descending order.
  • Print the list after sorting all its elements in ascending order.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ["hello", "this", "is", "btechgeeks"]
# Print the given original list.
print("The Given original list is :", gvn_lst)
# Apply sort() function to the given list by passing the argument as
# reverse = "True" to sort the given list elements in descending order.
gvn_lst.sort(reverse=True)
# Print the list after sorting all its elements in descending order.
print("The given list after sorting in descending order: ")
print(gvn_lst)

Output:

The Given original list is : ['hello', 'this', 'is', 'btechgeeks']
The given list after sorting in descending order: 
['this', 'is', 'hello', 'btechgeeks']
3)Sort with custom function using key

If you want to create your own sorting implementation, the sort() method accepts a key function as an optional parameter.

You can sort the given list based on the results of the key function.

list.sort(key=len)

Below is the implementation:

# Taking element to sort
def givenelement(element):
    return element[0]


# Give the list as static input and store it in a variable.
gvn_lst = [(1, 3), (4, 6), (2, 6), (5, 1)]
# sort the given list with the key
gvn_lst.sort(key=givenelement)
# print the given list
print('The given list after Sorting:', gvn_lst)

Output:

The given list after Sorting: [(1, 3), (2, 6), (4, 6), (5, 1)]

Method #2: Using Built-in Functions (User Input)

1) sort in Ascending Order

Approach:

  • Give the list as user input using list(), input(),and split() functions.
  • Store it in a variable.
  • Print the given original list.
  • Apply sort() function to the given list to sort the given list elements in ascending order.
  • Print the list after sorting all its elements in ascending order.
  • The Exit of Program.

Below is the implementation:

# Give the list as user input using list(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(input("Enter some random List Elements separated by spaces = ").split())
# Print the given original list.
print("The Given original list is :", gvn_lst)
# Apply sort() function to the given list to sort the given list elements in
# ascending order.
gvn_lst.sort()
# Print the list after sorting all its elements in ascending order.
print("The given list after sorting in ascending order: ", gvn_lst)

Output:

Enter some random List Elements separated by spaces = A R Q D I
The Given original list is : ['A', 'R', 'Q', 'D', 'I']
The given list after sorting in ascending order: ['A', 'D', 'I', 'Q', 'R']
2) sort in Descending Order

Approach:

  • Give the list as user input using list(), input(),and split() functions.
  • Store it in a variable.
  • Print the given original list.
  • Apply sort() function to the given list by passing the argument as reverse = “True” to sort the given list elements in descending order.
  • Print the list after sorting all its elements in ascending order.
  • The Exit of Program.

Below is the implementation:

# Give the list as user input using list(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(input("Enter some random List Elements separated by spaces = ").split())
# Print the given original list.
print("The Given original list is :", gvn_lst)
# Apply sort() function to the given list by passing the argument as
# reverse = "True" to sort the given list elements in descending order.
gvn_lst.sort(reverse=True)
# Print the list after sorting all its elements in descending order.
print("The given list after sorting in descending order: ")
print(gvn_lst)

Output:

Enter some random List Elements separated by spaces = good morning btechgeeks hello all
The Given original list is : ['good', 'morning', 'btechgeeks', 'hello', 'all']
The given list after sorting in descending order: 
['morning', 'hello', 'good', 'btechgeeks', 'all']

Covered all examples on python concepts and missed checking out the Python List Method Examples then go with the available link & gain more knowledge about List method concepts in python.

Python List sort() Method with Examples Read More »

Python List reverse() Method with Examples

In the previous article, we have discussed Python List remove() Method with Examples
List in Python:

Lists in Python are mutable sequences. They are extremely similar to tuples, except they do not have immutability constraints. Lists are often used to store collections of homogeneous things, but there is nothing stopping you from storing collections of heterogeneous items as well.

List reverse() Method in Python:

The reverse() method reverses the list’s elements.

Syntax:

list.reverse()

Parameters: This function has no parameters.

Return Value:

The reverse() method produces no output. It is used to update the existing list.

Examples:

Example1:

Input:

Given List = ['welcome', 'to', 'Python', 'programs']

Output:

The given original list: ['welcome', 'to', 'Python', 'programs']
The given list after reversing :  ['programs', 'Python', 'to', 'welcome']

Example2:

Input:

Given List = [10, 20, 30, 40, 50]

Output:

The given original list: [10, 20, 30, 40, 50]
The given list after reversing :  [50, 40, 30, 20, 10]

List reverse() Method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Print the given original list.
  • Apply reverse() function to the given list that reverses all the elements of the given list.
  • Print the list after reversing all its elements.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ["welcome", "to", "Python", "programs"]
# Print the given original list.
print("The given original list:", gvn_lst)
# Apply reverse() function to the given list that reverses all the elements of
# the given list.
gvn_lst.reverse()
# Print the list after reversing all its elements.
print("The given list after reversing : ", gvn_lst)

Output:

The given original list: ['welcome', 'to', 'Python', 'programs']
The given list after reversing :  ['programs', 'Python', 'to', 'welcome']

Method #2: Using Built-in Functions (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Print the given original list.
  • Apply reverse() function to the given list that reverses all the elements of the given list.
  • Print the list after reversing all its elements.
  • The Exit of Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Print the given original list.
print("The given original list:", gvn_lst)
# Apply reverse() function to the given list that reverses all the elements of
# the given list.
gvn_lst.reverse()
# Print the list after reversing all its elements.
print("The given list after reversing : ", gvn_lst)

Output:

Enter some random List Elements separated by spaces = 10 20 30 40 50
The given original list: [10, 20, 30, 40, 50]
The given list after reversing : [50, 40, 30, 20, 10]

Reversing a list Using Slicing Operator

Approach:

  • Give the list as static input and store it in a variable.
  • Print the given original list.
  • Reverse the elements of the given list using the slicing operator and store it in another variable.
  • Print the list after reversing all its elements.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ['good', 'morning', 'btechgeeks', 25, 35]
# Print the given original list.
print("The Given original list is :", gvn_lst)
# Reverse the elements of the given list using the slicing operator and
# store it in another variable.
reversee_lst = gvn_lst[::-1]
# Print the list after reversing all its elements.
print("The given list after reversing : ", reversee_lst)

Output:

The Given original list is : ['good', 'morning', 'btechgeeks', 25, 35]
The given list after reversing :  [35, 25, 'btechgeeks', 'morning', 'good']

Covered all examples on python concepts and missed checking out the Python List Method Examples then go with the available link & gain more knowledge about List method concepts in python.

Python List reverse() Method with Examples Read More »

Python List pop() Method with Examples

In the previous article, we have discussed Python List insert() Method with Examples
List in Python:

Lists in Python are mutable sequences. They are extremely similar to tuples, except they do not have immutability constraints. Lists are often used to store collections of homogeneous things, but there is nothing stopping you from storing collections of heterogeneous items as well.

List pop() Method in Python:

The pop() method removes the item at the specified index from the list and returns the item that was removed.

Note: By default, it removes the last element from the list.

Syntax:

list.pop(index)

Parameters

The pop() method only accepts one argument (index).

index: This is optional.

  • It is not required to pass an argument to the method. If no argument is provided, the default index -1 is used (index of the last item).
  • If the index passed to the method is not within the range, the IndexError: pop index out of range exception is thrown.

Return Value:

The pop() method returns the item at the specified index. This item has been removed from the list as well.

Examples:

Example1:

Input:

Given list = ['good', 'morning', 'btechgeeks', 4, 5, 6]
Given index = 2

Output:

The value returned is:  btechgeeks
The given list after poping 2 item =  ['good', 'morning', 4, 5, 6]

Example2:

Input:

Given list = ['hello', 'this', 'is', 'btechgeeks']

Output:

The value returned is:  btechgeeks
The given list after poping with giving an index is : ['hello', 'this', 'is']

List pop() Method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Give the number(index) as static input and store it in another variable.
  • Pass the given index as a parameter to the pop() function for the given list (which removes the element at the given index and returns the value that is removed).
  • Store it in another variable.
  • Print the above-returned value.
  • Print the given list after poping the item at the given index value.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ['good', 'morning', 'btechgeeks', 4, 5, 6]
# Give the number(index) as static input and store it in another variable.
gvn_indx = 2
# Pass the given index as a parameter to the pop() function for the given
# list (which removes the element at the given index and returns the value
# that is removed).
# Store it in another variable.
retrnvalu = gvn_lst.pop(gvn_indx)
# Print the above-returned value.
print("The value returned is: ", retrnvalu)
# Print the given list after poping the item at the given index value.
print("The given list after poping", gvn_indx, "item = ", gvn_lst)

Output:

The value returned is:  btechgeeks
The given list after poping 2 item =  ['good', 'morning', 4, 5, 6]

Method #2: Using Built-in Functions (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the number(index) as user input using the int(input()) function and store it in another variable.
  • Pass the given index as a parameter to the pop() function for the given list (which removes the element at the given index and returns the value that is removed).
  • Store it in another variable.
  • Print the above-returned value.
  • Print the given list after poping the item at the given index value.
  • The Exit of Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Give the number(index) as user input using the int(input()) function 
# and store it in another variable.
gvn_indx = int(input("Enter some random number = "))
# Pass the given index as a parameter to the pop() function for the given
# list (which removes the element at the given index and returns the value
# that is removed).
# Store it in another variable.
retrnvalu = gvn_lst.pop(gvn_indx)
# Print the above-returned value.
print("The value returned is: ", retrnvalu)
# Print the given list after poping the item at the given index value.
print("The given list after poping", gvn_indx, "item = ", gvn_lst)

Output:

Enter some random List Elements separated by spaces = 25 60 56 13 12
Enter some random number = 3
The value returned is: 13
The given list after poping 3 item = [25, 60, 56, 12]

Similarly, pop without an index and negative index

Approach:

  • Give the list as static input and store it in a variable.
  • Give the negative number(index) as static input and store it in another variable.
  • Pass the given index as a parameter to the pop() function for the given list (which removes the element at the given index and returns the value that is removed).
  • Store it in another variable.
  • Print the above-returned value.
  • Print the given list after poping the item at the given index value.
  • Apply the pop() function to the given list without giving an index and get the value that is returned.
  • Store it in another variable.
  • Print the above-returned value.
  • Print the given list after applying the pop() function.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ['hello', 'this', 'is', 'btechgeeks']
# Give the negative number(index) as static input and store it in
# another variable.
gvn_indx = -3
# Pass the given index as a parameter to the pop() function for the given
# list (which removes the element at the given index and returns the value
# that is removed).
# Store it in another variable.
retrnvalu = gvn_lst.pop(gvn_indx)
# Print the above-returned value.
print("The value returned is: ", retrnvalu)
# Print the given list after poping the item at the given index value.
print("The given list after poping", gvn_indx, "item = ", gvn_lst)
# Apply pop() function to the given list without giving an index and get the
# value that is returned.
# Store it in another variable.
retrnvalu1 = gvn_lst.pop()
# Print the above-returned value.
print("The value returned is: ", retrnvalu1)
# Print the given list after applying pop() function
print("The given list is after applying pop() function:", gvn_lst)

Output:

The value returned is:  this
The given list after poping -3 item =  ['hello', 'is', 'btechgeeks']
The value returned is:  btechgeeks
The given list is after applying pop() function: ['hello', 'is']

Know about the syntax and usage of functions to manipulate lists with the provided Python List Method Examples and use them.

Python List pop() Method with Examples Read More »

Python List insert() Method with Examples

In the previous article, we have discussed Python List copy() Method with Examples
List in Python:

Lists in Python are mutable sequences. They are extremely similar to tuples, except they do not have immutability constraints. Lists are often used to store collections of homogeneous things, but there is nothing stopping you from storing collections of heterogeneous items as well.

List insert() Method in Python:

Inserts the specified value at the specified position using the insert() method.

Syntax:

list.insert(position, element)

Parameters

position: This is Required. A number indicating where the value should be inserted.

element: This is Required. Any type of element (string, number, object etc.)

Return Value:

The insert() method produces no results; it returns None. It only makes changes to the current list.

Examples:

Example1:

Input:

Given List = ["hello", "is", "btechgeeks"]
Given position = 1
Given element = "this"

Output:

The given list after inserting the given element: 
['hello', 'this', 'is', 'btechgeeks']

Example2:

Input:

Given List = ["good", "morning", "btechgeeks"]
Given position = 1
Given Tuple = (1, 3, 5, 7)

Output:

The given list after inserting the given Tuple: 
['good', (1, 3, 5, 7), 'morning', 'btechgeeks']

List insert() Method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

1) Inserting an element to the List

Approach:

  • Give the list as static input and store it in a variable.
  • Give the position as static input and store it in another variable.
  • Give the element as static input and store it in another variable.
  • Pass the given position and given element as arguments to the insert() function for the given list to insert the given element at the given position.
  • Print the given list after inserting the given element.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ["hello", "is", "btechgeeks"]
# Give the position as static input and store it in another variable.
gvn_positin = 1
# Give the element as static input and store it in another variable.
gvn_elemnt = "this"
# Pass the given position and given element as arguments to the insert()
# function for the given list to insert the given element at the given position.
gvn_lst.insert(gvn_positin, gvn_elemnt)
# Print the given list after inserting the given element.
print("The given list after inserting the given element: ")
print(gvn_lst)

Output:

The given list after inserting the given element: 
['hello', 'this', 'is', 'btechgeeks']
2)Inserting tuple as an element to the List

Approach:

  • Give the list as static input and store it in a variable.
  • Give the position as static input and store it in another variable.
  • Give the tuple as static input and store it in another variable.
  • Pass the given position and given tuple as arguments to the insert() function for the given list to insert the given tuple at the given position.
  • Print the given list after inserting the given tuple.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ["good", "morning", "btechgeeks"]
# Give the position as static input and store it in another variable.
gvn_positin = 1
# Give the tuple as static input and store it in another variable.
gvn_tupl = (1, 3, 5, 7)
# Pass the given position and given tuple as arguments to the insert()
# function for the given list to insert the given tuple at the given position.
gvn_lst.insert(gvn_positin, gvn_tupl)
# Print the given list after inserting the given Tuple.
print("The given list after inserting the given Tuple: ")
print(gvn_lst)

Output:

The given list after inserting the given Tuple: 
['good', (1, 3, 5, 7), 'morning', 'btechgeeks']

Method #2: Using Built-in Functions (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the position as user input using the int(input()) function and store it in another variable.
  • Give the element as user input using the input() function and store it in another variable.
  • Pass the given position and given element as arguments to the insert() function for the given list to insert the given element at the given position.
  • Print the given list after inserting the given element.
  • The Exit of Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Give the position as user input using the int(input()) function and 
# store it in another variable.
gvn_positin = int(input("Enter some random number = "))
# Give the element as user input using the input() function and 
# store it in another variable.
gvn_elemnt = input("Enter some random string = ")
# Pass the given position and given element as arguments to the insert()
# function for the given list to insert the given element at the given position.
gvn_lst.insert(gvn_positin, gvn_elemnt)
# Print the given list after inserting the given element.
print("The given list after inserting the given element: ")
print(gvn_lst)

Output:

Enter some random List Elements separated by spaces = 10 20 30 40 70
Enter some random number = 2
Enter some random string = hello
The given list after inserting the given element: 
[10, 20, 'hello', 30, 40, 70]

Know about the syntax and usage of functions to manipulate lists with the provided Python List Method Examples and use them.

Python List insert() Method with Examples Read More »

Python help() function with Examples | Help function in Python

In the previous article, we have discussed Python String encode() Method with Examples
help() Function in Python:

The help() method invokes or calls Python’s built-in help system.

The Python help function displays documentation for modules, functions, classes, keywords, and so on.

Syntax:

help(object)

Parameters

The help() method only accepts one parameter.

object: This is optional. you want to generate help and support from the given object

For interactive use, the help() method is used. When you need assistance writing Python programs and using Python modules, it is recommended that you try it in your interpreter.

1)Note: It should be noted that object is passed to help() (not a string)

For Example:

Input:

help(list)

Output:

Help on class list in module builtins:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __iadd__(self, value, /)
 |      Implement self+=value.
 |  
 |  __imul__(self, value, /)
 |      Implement self*=value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __reversed__(...)
 |      L.__reversed__() -- return a reverse iterator over the list
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __setitem__(self, key, value, /)
 |      Set self[key] to value.
 |  
 |  __sizeof__(...)
 |      L.__sizeof__() -- size of L in memory, in bytes
 |  
 |  append(...)
 |      L.append(object) -> None -- append object to end
 |  
 |  clear(...)
 |      L.clear() -> None -- remove all items from L
 |  
 |  copy(...)
 |      L.copy() -> list -- a shallow copy of L
 |  
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value
 |  
 |  extend(...)
 |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
 |  
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |  
 |  insert(...)
 |      L.insert(index, object) -- insert object before index
 |  
 |  pop(...)
 |      L.pop([index]) -> item -- remove and return item at index (default last).
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(...)
 |      L.remove(value) -> None -- remove first occurrence of value.
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(...)
 |      L.reverse() -- reverse *IN PLACE*
 |  
 |  sort(...)
 |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

Explanation:

In this way we get the output which displays the documentation for modules, 
functions, classes, keywords, and so on.

similarly, try out for these

>>help(dict)
>>help(print)
>>help(tuple)
>>help([4,5,6])

If a string is passed as an argument, the name of a module, function, class, method, keyword, or documentation topic is printed, as well as a help page.

2)Note: It should be noted that string is passed as an argument to help()

When a string is passed as an argument, it is looked up as the name of a module, function, class, method, keyword, or documentation topic and a help page is printed.

Check it out for the following Examples.

Input:

help('hello')

Output:

No Python documentation found for 'hello'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.

similarly, try out for these

>>help('print')
>>help('uvw')

Input:

from math import * 
help('math.pow')

Output:

Help on built-in function pow in math:

math.pow = pow(...)
    pow(x, y)
    
    Return x**y (x to the power of y).

3)Note: It should be noted that no argument is passed to help()

If no arguments are provided, Python’s help utility (interactive help system) is launched on the console.

>>help()

Then, enter the topic name to get help with writing Python programmes and using Python modules.

As an example, Check it out for the following Examples:

help > True
help > 'print'
help > print

To return to the interpreter and exit the help utility, type quit and press enter.

help > quit

Find a Comprehensive Collection of Python Built in Functions that you need to be aware of and use them as a part of your program.

Python help() function with Examples | Help function in Python Read More »

Python String splitlines() Method with Examples

In the previous article, we have discussed Python String maketrans() Method with Examples
splitlines() Method in Python:

The splitlines() method divides(splits) a string into a list of lines. Line breaks are used for splitting.

Syntax:

string.splitlines(keeplinebreaks)

Parameters

keeplinebreaks: Optional. Specifies whether or not line breaks should be included (True) (False). False is the default value.

Return Value: 

splitlines() returns a list of the string’s lines.

If no line break characters are present, it returns a list with a single item (a single line).

splitlines() divides lines at the following points:

  • \n – Line Feed
  • \r – Carriage Return
  • \r\n – Carriage Return + Line Feed
  • \v or \x0b – Line Tabulation
  • \f or \x0c – Form Feed
  • \x1c – File Separator
  • \x1d – Group Separator
  • \x1e – Record Separator
  • \x85 – Next Line (C1 Control Code)
  • \u2028 – Line Separator
  • \u2029 – Paragraph Separator

Examples:

Example1:

Input:

Given string = 'welcome to\n Python\n programs\n'

Output:

The given string after spliting : ['welcome to', ' Python', ' programs']

Example2:

Input:

Given string = 'hello all good morning'

Output:

The given string after spliting : ['hello all good morning']

Example3:

Input:

Given string = 'welcome to\n Python\n programs\n'

Output:

The given string after spliting by passing the true parameter:
['welcome to\n', ' Python\n', ' programs\n']

String splitlines() Method Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Apply splitlines() function to the given string that divides(splits) a given string into a list of lines.
  • Store it in another variable.
  • Print the result after splitting the given string.
  • Apply splitlines() function to the given string by passing the parameter as True and printing the result.
  • Give the second string as static input and store it in a variable.
  • Apply splitlines() function to the given second string and print the result.
  • The Exit of Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = 'welcome to\n Python\n programs\n'
# Apply splitlines() function to the given string that divides(splits) a
# given string into a list of lines.
# Store it in another variable.
splt_str = gvn_str.splitlines()
# Print the result after splitting the given string.
print("The given string after spliting :", splt_str)
# Apply splitlines() function to the given string by passing the parameter
# as True and printing the result.
print("The given string after spliting :", gvn_str.splitlines(True))
# Give the second string as static input and store it in a variable.
gvn_scndstr = 'hello all good morning'
# Apply splitlines() function to the given second string and print the result.
print("The given string after spliting :", gvn_scndstr.splitlines())

Output:

The given string after spliting : ['welcome to', ' Python', ' programs']
The given string after spliting : ['welcome to\n', ' Python\n', ' programs\n']
The given string after spliting : ['hello all good morning']

Go through our tutorial and learn about various Python String Method Examples and learn how to apply the knowledge while dealing with strings.

Python String splitlines() Method with Examples Read More »

Python String encode() Method with Examples

In the previous article, we have discussed Python Program for Pass Statement with Examples
String encode() Method in Python:

The encode() method encodes the string using the encoding specified. When no encoding is specified, UTF-8 is used.

Syntax:

string.encode(encoding=encoding, errors=errors)

Parameter Values:

encoding: This is Optional. A String indicating the encoding to be used. UTF-8 is the default.

errors: This is Optional. The error method is specified as a String. The following are legal values:

  • backslashreplace – employs a backslash in place of the unencoded character
  • ignore – does not encode characters that cannot be encoded.
  • namereplace – replaces the character with text that describes the character.
  • strict – On failure, the default raises an error.
  • replace – inserts a question mark in place of the character.
  • xmlcharrefreplace – a character is replaced with an xml character.

Examples:

Example1:

Input:

Given string =  "Welcome to Pythön-prögrams"

Output:

b'Welcome to Pyth\\xf6n-pr\\xf6grams'
b'Welcome to Pythn-prgrams'
b'Welcome to Pyth\\N{LATIN SMALL LETTER O WITH DIAERESIS}n-pr\\N{LATIN SMALL LETTER O WITH DIAERESIS}grams'
b'Welcome to Pyth?n-pr?grams'
b'Welcome to Pyth&#246;n-pr&#246;grams'

Example2:

Input:

Given string = "Hello this is vikråm"

Output:

b'Hello this is vikr\\xe5m'
b'Hello this is vikrm'
b'Hello this is vikr\\N{LATIN SMALL LETTER A WITH RING ABOVE}m'
b'Hello this is vikr?m'
b'Hello this is vikr&#229;m'

String encode() Method Examples in Python

Method #1: Using Built-in Functions (Static Input)

These examples demonstrate the use of ascii encoding and a character that cannot be encoded, with various errors:

Approach:

  • Give the string as static input() and store it in a variable.
  • Give the encoding value as ascii and errors as “backslashreplace” for the given string using the encode function and print it.
  • Here “backslashreplace” employs a backslash in place of the unencoded character.
  • Give the encoding value as ascii and errors as “ignore” for the given string using the encode function and print it.
  • Here “ignore” does not encode characters that cannot be encoded.
  • Give the encoding value as ascii and errors as “namereplace” for the given string using the encode function and print it.
  • Here “namereplace” replaces the character with text that describes the character.
  • Give the encoding value as ascii and errors as “replace” for the given string using the encode function and print it.
  • Here “replace” inserts a question mark in place of the character.
  • Give the encoding value as ascii and errors as “xmlcharrefreplace” for the given string using the encode function and print it.
  • Here “xmlcharrefreplace” is replacing a character with an xml character.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input() and store it in a variable.
gvn_str = "Welcome to Pythön-prögrams"
# Give the encoding value as ascii and errors as "backslashreplace" for the
# given string using the encode function and print it.
# Here "backslashreplace" employs a backslash in place of the unencoded character.
print(gvn_str.encode(encoding="ascii", errors="backslashreplace"))
# Give the encoding value as ascii and errors as "ignore" for the given
# string using the encode function and print it.
# Here "ignore" does not encode characters that cannot be encoded.
print(gvn_str.encode(encoding="ascii", errors="ignore"))
# Give the encoding value as ascii and errors as "namereplace" for the given
# string using the encode function and print it.
# Here "namereplace" replaces the character with text that describes the character.
print(gvn_str.encode(encoding="ascii", errors="namereplace"))
# Give the encoding value as ascii and errors as "replace" for the given
# string using the encode function and print it.
# Here "replace" inserts a question mark in place of the character.
print(gvn_str.encode(encoding="ascii", errors="replace"))
# Give the encoding value as ascii and errors as "xmlcharrefreplace" for the
# given string using the encode function and print it.
# Here "xmlcharrefreplace" is replacing a character with an xml character.
print(gvn_str.encode(encoding="ascii", errors="xmlcharrefreplace"))

Output:

b'Welcome to Pyth\\xf6n-pr\\xf6grams'
b'Welcome to Pythn-prgrams'
b'Welcome to Pyth\\N{LATIN SMALL LETTER O WITH DIAERESIS}n-pr\\N{LATIN SMALL LETTER O WITH DIAERESIS}grams'
b'Welcome to Pyth?n-pr?grams'
b'Welcome to Pyth&#246;n-pr&#246;grams'

Method #2: UTF-8 encoding to the given string (Static Input)

Below is the implementation:

gvn_str = "Hello this is vikråm"
rslt = gvn_str.encode()
print(rslt)

Output:

b'Hello this is vikr\xc3\xa5m'

String Encoding:

Strings have been stored as Unicode since Python 3.0, which means that each character in the string is represented by a code point. As a result, each string is simply a series of Unicode code points.

The sequence of code points is converted into a set of bytes for efficient storage of these strings. Encoding is the name given to this process.

There are numerous encodings available, each of which treats a string differently. Popular encodings include utf-8, ascii, and others.

Using the string encode() method, you can convert unicode strings to any Python encoding. Python’s default encoding is utf-8.

Go through our tutorial and learn about various Python String Method Examples and learn how to apply the knowledge while dealing with strings.

 

Python String encode() Method with Examples Read More »

Python String maketrans() Method with Examples

In the previous article, we have discussed Python String isupper() Method Examples
maketrans() Method in Python:

The string maketrans() method returns a translation mapping table that can be used by the translate() method.

To put it simply, the maketrans() method is a static method that generates a one-to-one mapping of a character to its translation/replacement.

Each character is given a Unicode representation for translation.

When the translate() method is called, this translation mapping is used to replace a character with its mapped character.

Syntax:

string.maketrans(x, y, z)

Parameters:

x: If there is only one argument, it must be a dictionary.
A 1-to-1 mapping from a single character string to its translation OR a Unicode number (97 for ‘a’) to its translation should be included in the dictionary.

y: If two arguments are passed, they must be of equal length.
Each character in the first string is a replacement for the index in the second string that corresponds to it.

z: If three arguments are passed, the third argument’s characters are mapped to None.

Return Value:

The maketrans() method returns a translation table that contains a one-to-one mapping of a Unicode ordinal to its translation/replacement.

Examples:

Example1:

maketrans() Translation table using a dictionary
gvn_dict = {"a": "100", "b": "200", "c": "300"}
gvn_str = "abc"
print(gvn_str.maketrans(gvn_dict))

gvn_dict = {97: "100", 98: "200", 99: "300"}
gvn_str = "abc"
print(gvn_str.maketrans(gvn_dict))

Output:

{97: '100', 98: '200', 99: '300'}
{97: '100', 98: '200', 99: '300'}

Explanation:

A dictionary gvn_dict is defined here. It has a mapping of the characters a,b, and c to 100,200, and 300, respectively.

maketrans() generates a mapping from the character’s Unicode ordinal to its translation.

As a result, 97 (‘a’) corresponds to ‘100,’ 98 ‘b’ corresponds to 200, and 99 ‘c’ corresponds to 300. The output of both dictionaries demonstrates this.

In addition, if two or more characters are mapped in the dictionary, an exception is raised.

Example2:

maketrans() Translation table using two strings
gvn_fststr = "abc"
gvn_scndstr = "def"
gvn_str = "abc"
print(gvn_str.maketrans(gvn_fststr, gvn_scndstr))

gvn_fststr = "abc"
gvn_scndstr = "defghi"
gvn_str = "abc"
print(gvn_str.maketrans(gvn_fststr, gvn_scndstr))

Output:

Traceback (most recent call last):
  File "/home/d57f28dec313688f30b673716d7d7ec8.py", line 9, in <module>
    print(gvn_str.maketrans(gvn_fststr, gvn_scndstr))
ValueError: the first two maketrans arguments must have equal length

Explanation:

First, two strings of equal length are defined: abc and def. The corresponding translation is then generated.

Only printing the first translation results in a 1-to-1 mapping from each character’s Unicode ordinal in the first string to the same indexed character in the second string.

In this case, 97 (‘a’) corresponds to 100 (‘d’), 98 (‘b’) corresponds to 101 (‘e’), and 99 (‘c’) corresponds to 102 (‘f’).

Attempting to create a translation table for strings of unequal length raises a ValueError exception, indicating that the strings must be of equal length.

Example3:

maketrans() Translation table with removable string
gvn_fststr = "abc"
gvn_scndstr = "def"
gvn_thrdstr = "abd"
gvn_str = "abc"
print(gvn_str.maketrans(gvn_fststr, gvn_scndstr, gvn_thrdstr))

Output:

{97: None, 98: None, 99: 102, 100: None}

Explanation:

The mapping between the two strings firstString and secondString is created first.

The third argument, thirdString, then resets each character’s mapping to None and creates a new mapping for non-existent characters.

In this case, thirdString resets the mappings of 97 (‘a’) and 98 (‘b’) to None, as well as creating a new mapping for 100 (‘d’) that is also mapped to None.

Go through our tutorial and learn about various Python String Method Examples and learn how to apply the knowledge while dealing with strings.

Python String maketrans() Method with Examples Read More »

Python Program for Pass Statement with Examples

pass Statement in Python:

The pass statement serves as a placeholder for additional code.

The pass statement is a null statement in Python programming. The difference between a comment and a pass statement in Python is that while a comment is completely ignored by the interpreter, a pass statement is not.

When the pass is executed, however, nothing happens. It has no effect on the operation (NOP).

Assume we have a loop or a function that has not yet been implemented but that we intend to do so in the future. They cannot exist with an empty body. The interpreter would return an error message. As a result, we use the pass statement to create a body that does nothing.

Syntax:

pass
In a function definition, use the pass keyword as follows:

Example:

# Without the pass statement, having an empty function definition like this
# would result in an error.
def empty_function():
    pass

Output:

Explanation:

we don't get any output since it is an empty function.But, Without the pass 
statement, having an empty function definition like this would 
result in an error.
In a class definition, use the pass keyword as follows:

Example:

# Without the pass statement, having an empty class definition like this 
# would result in an error.
class Person:
  pass

In loops, use the pass keyword as follows:

Example:

gvn_seqnce = {'a', 'b', 'c', 'd'}
for itr in gvn_seqnce:
    pass

Program for pass Statement in Python

Method #1: Using Built-in Functions (Static Input)

In an, if statement, use the pass keyword as follows:

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Check if the given second number is greater than the first number using the if conditional statement.
  • If it is true, then give a pass statement.
  • Else print the given first and second numbers.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
numb1 = 33
# Give the second number as static input and store it in another variable.
numb2 = 50
# Check if the given second number is greater than the first number using
# the if conditional statement.
if numb2 > numb1:
    # If it is true, then give a pass statement.
    pass
else:
    # Else print the given first and second numbers.
    print(numb1)
    print(numb2)

Output:

Explanation:

Here, We don't get any output as we gave a pass statement if the condition
satisfies.

Method #2: Using Built-in Functions (User Input)

Approach:

  • Give the first number as user input using the int(input()) and store it in a variable.
  • Give the second number as user input using the int(input()) and store it in another variable.
  • Check if the given second number is greater than the first number using the if conditional statement.
  • If it is true, then give a pass statement.
  • Else print the given first and second numbers.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as user input using the int(input()) and store it in a variable.
numb1 = int(input("Enter some random number = "))
# Give the second number as user input using the int(input()) and store it in another variable.
numb2 = int(input("Enter some random number = "))
# Check if the given second number is greater than the first number using
# the if conditional statement.
if numb2 > numb1:
    # If it is true, then give a pass statement.
    pass
else:
    # Else print the given first and second numbers.
    print(numb1)
    print(numb2)

Output:

Enter some random number = 100
Enter some random number = 20
100
20

Find a Comprehensive Collection of Python Built in Functions that you need to be aware of and use them as a part of your program.

Python Program for Pass Statement with Examples Read More »

Python List copy() Method with Examples

In the previous article, we have discussed Python List clear() Method with Examples
List in Python:

Lists in Python are mutable sequences. They are extremely similar to tuples, except they do not have immutability constraints. Lists are often used to store collections of homogeneous things, but there is nothing stopping you from storing collections of heterogeneous items as well.

List copy() Method in Python:

The copy() method returns a duplicate (copy) of the specified list.

Syntax:

list.copy()

Parameter Values: This method has no parameters.

Return Value:

A new list is returned by the copy() function. It makes no changes to the original list.

Examples:

Example1:

Input:

Given List = ['hello', 'this', 'is', 'btechgeeks']

Output:

The given list is :  ['hello', 'this', 'is', 'btechgeeks']
The new list after applying copy() function is :
['hello', 'this', 'is', 'btechgeeks']

Example2:

Input:

Given List = [20, 40, 60, 80, 100]

Output:

The given list is :  [20, 40, 60, 80, 100]
The new list after applying copy() function is :
[20, 40, 60, 80, 100]

List copy() Method with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Print the given list.
  • Copy all the elements of the given list into the new list using the copy() function and store it in another variable.
  • Print the above new list which is the duplicate of the given list.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ["hello", "this", "is", "btechgeeks"]
# Print the given list.
print("The given list is : ", gvn_lst)
# Copy all the elements of the given list into the new list using the copy()
# function and store it in another variable.
new_lst = gvn_lst.copy()
# Print the above new list which is the duplicate of the given list.
print("The new list after applying copy() function is :")
print(new_lst)

Output:

The given list is :  ['hello', 'this', 'is', 'btechgeeks']
The new list after applying copy() function is :
['hello', 'this', 'is', 'btechgeeks']

Method #2: Using Built-in Functions (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Print the given list.
  • Copy all the elements of the given list into the new list using the copy() function and store it in another variable.
  • Print the above new list which is the duplicate of the given list.
  • The Exit of Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Print the given list.
print("The given list is : ", gvn_lst)
# Copy all the elements of the given list into the new list using the copy()
# function and store it in another variable.
new_lst = gvn_lst.copy()
# Print the above new list which is the duplicate of the given list.
print("The new list after applying copy() function is :")
print(new_lst)

Output:

Enter some random List Elements separated by spaces = 20 40 60 80 100
The given list is : [20, 40, 60, 80, 100]
The new list after applying copy() function is :
[20, 40, 60, 80, 100]

copying List using ‘=’ Operator

To copy a list, we can also use the = operator.

However, there is one drawback to copying lists in this manner. When you change a new list, you also change the old list. It’s because the new list refers to or points to the same old list object.

Example:

Approach:

  • Give the list as static input and store it in a variable.
  • Copy the elements of the given list into the new list using the ‘=’ operator.
  • Store it in another variable.
  • Add an element to the new list using the append() function.
  • Print the given original list.
  • Print the new list obtained.
  • The Exit of Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = [20, 40, 60, 80, 100]
# copy the elements of the given list into new list using the '=' operator
# store it in another variable.
new_lst = gvn_lst
# Add an element to the new list using the append() function
new_lst.append('python')
# Print the given original list.
print("The given original list is:", gvn_lst)
# Print the new list obtained.
print("The new list obtained is :", new_lst)

Output:

The given original list is: [20, 40, 60, 80, 100, 'python']
The new list obtained is : [20, 40, 60, 80, 100, 'python']

copying List using Slicing

For Example:

# Give the list as static input and store it in a variable.
gvn_lst = ['good', 'morning', 'btechgeeks', 123]
# copy the elements of the given list into new list using the slicing.
# store it in another variable.
new_lst = gvn_lst[:]
# Add an element to the new list using the append() function
new_lst.append(1000)
# Print the given original list.
print("The given original list is:", gvn_lst)
# Print the new list obtained.
print("The new list obtained is :", new_lst)

Output:

The given original list is: ['good', 'morning', 'btechgeeks', 123]
The new list obtained is : ['good', 'morning', 'btechgeeks', 123, 1000]

Know about the syntax and usage of functions to manipulate lists with the provided Python List Method Examples and use them.

Python List copy() Method with Examples Read More »