Author name: Vikram Chiluka

Python min() Function with Examples

In the previous article, we have discussed Python max() Function with Examples
min() Function in Python:

The min() function returns the item with the lowest value or the item in an iterable with the lowest value.

If the values are strings, they are compared alphabetically.

Syntax:

min(iterable)

or

min(n1, n2, n3,........)

Parameters

iterable: An iterable that compares one or more items.

n1, n2, n3,……..: a single or multiple items to compare.

Return Value:

min() returns the iterable’s smallest element.

Examples:

Example1:

Input:

Given List = [1, 2, 5, 6, 15, 7]

Output:

The smallest number in the given list = 1

Example2:

Input:

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

Output:

The smallest string in the given list (alphabetically ordered) is :
btechgeeks

Note:

If the items in an iterable are strings, the smallest(alphabetically ordered) 
item is returned.

min() Function with Examples in Python

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

1)For Number List

Approach:

  • Give the list as static input and store it in a variable.
  • Pass the given list as an argument to the min() function to get the smallest element in the given list.
  • Store it in another variable.
  • Print the smallest element(number) in the given list.
  • The Exit of the program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = [1, 2, 5, 6, 15, 7]
# Pass the given list as an argument to the min() function to get the smallest
# element in the given list.
# Store it in another variable.
smallst_numb = min(gvn_lst)
# Print the smallest element(number) in the given list.
print("The smallest number in the given list =", smallst_numb)

Output:

The smallest number in the given list = 1
2)For String List

Similarly, do the same to get the smallest string in the given list.

Note: If the items in an iterable are strings, the smallest (alphabetically ordered) item is returned.

Approach:

  • Give the list (string list) as static input and store it in a variable.
  • Pass the given list as an argument to the min() function to get the smallest string in the given list. If the items in an iterable are strings, the smallest (alphabetically ordered) item is returned.
  • Store it in another variable.
  • Print the smallest string in the given list (alphabetically ordered).
  • The Exit of the program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_strlst = ["hello", "this", "is", "btechgeeks"]
# Pass the given list as an argument to the min() function to get the smallest
# string in the given list.If the items in an iterable are strings,
# the smallest (alphabetically ordered) item is returned.
# Store it in another variable.
smallst_str = min(gvn_strlst)
# Print the smallest string in the given list (alphabetically ordered).
print("The smallest string in the given list (alphabetically ordered) is :")
print(smallst_str)

Output:

The smallest string in the given list (alphabetically ordered) is :
btechgeeks
3)Passing multiple arguments

To get the smallest number from the given numbers.

# Give some random numbers as arguments to the min() function.
smallst_numb = min(5, 10, -1, 9, 6)
# Print the smallest number from the given numbers
print("The smallest number from the given numbers = ", smallst_numb)

Output:

The smallest number from the given numbers =  -1

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

1)For Number List

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Pass the given list as an argument to the min() function to get the smallest element in the given list.
  • Store it in another variable.
  • Print the smallest element(number) in the given list.
  • The Exit of the 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()))
# Pass the given list as an argument to the min() function to get the smallest
# element in the given list.
# Store it in another variable.
smallst_numb = min(gvn_lst)
# Print the smallest element(number) in the given list.
print("The smallest number in the given list =", smallst_numb)

Output:

Enter some random List Elements separated by spaces = 6 2 1 -2 0
The smallest number in the given list = -2
2)For String List

Approach:

  • Give the list (string list) as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Pass the given list as an argument to the min() function to get the smallest string in the given list. If the items in an iterable are strings, the smallest (alphabetically ordered) item is returned.
  • Store it in another variable.
  • Print the smallest string in the given list (alphabetically ordered).
  • The Exit of the program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_strlst = list(input(
   'Enter some random List Elements separated by spaces = ').split())
# Pass the given list as an argument to the min() function to get the smallest
# string in the given list.If the items in an iterable are strings,
# the smallest (alphabetically ordered) item is returned.
# Store it in another variable.
smallst_str = min(gvn_strlst)
# Print the smallest string in the given list (alphabetically ordered).
print("The smallest string in the given list (alphabetically ordered) is :")
print(smallst_str)

Output:

Enter some random List Elements separated by spaces = good morning all
The smallest string in the given list (alphabetically ordered) is :
all

Fed up with searching various pages for the list of Python Built in Functions? Look at the tutorial linked here and explore all coding samples of built-in functions of python.

 

Python min() Function with Examples Read More »

Python next() Function with Examples

next() Function in Python:

The next() function returns the iterator’s next item.

You can specify a default return value to be returned if the iterable has reached its limit or end.

Syntax:

next(iterable, default)

Parameters

iterable: This is required. It is an iterable object.

default: This is Optional. If the iterable has reached its limit or end, this is the default value to return.

Return Value: 

  • The next() function returns the iterator’s next item.
  • If the iterator runs out of values, it returns the value passed as an argument.
  • If the default parameter is omitted and the iterator becomes exhausted, the StopIteration exception is thrown.

Examples:

Example1:

Input:

Given List =  ['good', 'morning', 'btechgeeks']

Output:

good
morning
btechgeeks
Traceback (most recent call last):
File "jdoodle.py", line 13, in <module>
print(next(iteratr))
StopIteration

Explanation

Here it prints the iterator value of the list element and increase the 
iterator to next element. 
It raises an errors when it exceeds the length of the list.

Example2:

Input:

Given List = ['good', 'morning', 'btechgeeks']
default value = hello

Output:

good
morning
btechgeeks
hello

Explanation

Here it prints the iterator value of the list element and increase the 
iterator to next element. 
When it exceeds the length of the list it prints the default value.

next() Function with Examples in Python

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

1)Without default value

Approach:

  • Give the list as static input and store it in a variable.
  • Convert the given list to an iterator using the iter() function and store it in another variable.
  • Apply the next() function to the above iterator to get the next item in the given list.
  • Store it in another variable.
  • Similarly, do the same till the end of the list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ['good', 'morning', 'btechgeeks']
# Convert the given list to an iterator using the iter() function and
# store it in another variable.
iteratr = iter(gvn_lst)
# Apply the next() function to the above iterator to get the next item in the
# given list.
# Store it in another variable.
print(next(iteratr))
# Similarly, do the same till the end of the list.
print(next(iteratr))
print(next(iteratr))
print(next(iteratr))

Output:

good
morning
btechgeeks
Traceback (most recent call last):
File "jdoodle.py", line 13, in <module>
print(next(iteratr))
StopIteration

Explanation

Here it prints the iterator value of the list element and increase iterator to
next element. 
It raises an errors when it exceeds the length of the list.
2)With the default value

Approach:

  • Give the list as static input and store it in a variable.
  • Give the default value as static input and store it in another variable.
  • Convert the given list to an iterator using the iter() function and store it in another variable.
  • Pass the above iterator and default value as the arguments to the given list to get the next item in the given list.
  • Store it in another variable.
  • Similarly, do the same till the end of the list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ['good', 'morning', 'btechgeeks']
# Give the default value as static input and store it in another variable.
gvn_defalt_valu = 'hello'
# Convert the given list to an iterator using the iter() function and
# store it in another variable.
iteratr = iter(gvn_lst)
# Pass the above iterator and default value as the arguments to the given list to
# get the next item in the given list.
# Store it in another variable.
print(next(iteratr, gvn_defalt_valu))
# Similarly, do the same till the end of the list.
print(next(iteratr, gvn_defalt_valu))
print(next(iteratr, gvn_defalt_valu))
print(next(iteratr, gvn_defalt_valu))

Output:

good
morning
btechgeeks
hello

Explanation

Here it prints the iterator value of the list element and increase iterator to
next element. 
When it exceeds the length of the list it prints the default value.

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

1)Without default value

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Convert the given list to an iterator using the iter() function and store it in another variable.
  • Apply the next() function to the above iterator to get the next item in the given list.
  • Store it in another variable.
  • Similarly, do the same till the end of the list.
  • The Exit of the 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()))
# Convert the given list to an iterator using the iter() function and
# store it in another variable.
iteratr = iter(gvn_lst)
# Apply the next() function to the above iterator to get the next item in the
# given list.
# Store it in another variable.
print(next(iteratr))
# Similarly, do the same till the end of the list.
print(next(iteratr))
print(next(iteratr))
print(next(iteratr))

Output:

Enter some random List Elements separated by spaces = 10 20 30
10
20
30
Traceback (most recent call last):
File "jdoodle.py", line 15, in <module>
print(next(iteratr))
StopIteration
2)With the default value

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the default value as a user input using the int(input()) function and store it in another variable.
  • Convert the given list to an iterator using the iter() function and store it in another variable.
  • Pass the above iterator and default value as the arguments to the given list to get the next item in the given list.
  • Store it in another variable.
  • Similarly, do the same till the end of the list.
  • The Exit of the 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 default value as a user input using the int(input()) function and 
# store it in another variable.
gvn_defalt_valu = int(input("Enter some random number = "))
# Convert the given list to an iterator using the iter() function and
# store it in another variable.
iteratr = iter(gvn_lst)
# Pass the above iterator and default value as the arguments to the given list to
# get the next item in the given list.
# Store it in another variable.
print(next(iteratr, gvn_defalt_valu))
# Similarly, do the same till the end of the list.
print(next(iteratr, gvn_defalt_valu))
print(next(iteratr, gvn_defalt_valu))
print(next(iteratr, gvn_defalt_valu))

Output:

Enter some random List Elements separated by spaces = 10 20 30 
Enter some random number = 40
10
20
30
40

 

Python next() Function with Examples Read More »

Python locals() Function with Examples

In the previous article, we have discussed Python hasattr() Method with Examples
locals() Function in Python:

The locals() method updates the current local symbol table and returns a dictionary of its contents.

A symbol table is a data structure maintained by a compiler that contains all necessary program information.

Variable names, methods, classes, and so on are examples of this.

There are two types of symbol tables.

  1. Global symbol table
  2. Local symbol table

A global symbol table stores all information related to the program’s global scope and is accessed in Python via the globals() method.

All functions and variables that are not associated with any class or function are included in the global scope.

Similarly, the Local symbol table stores all information related to the program’s local scope and is accessed in Python via the locals() method.

The local scope could be within a function, a class, or something else.

Syntax:

locals()

Parameter Values: The locals() method does not accept any parameters.

Return Value:

The dictionary associated with the current local symbol table is updated and returned by the locals() method.

locals() Function with Examples in Python

Using Built-in Functions (Static Input)

1)How does Python’s globals() method work?

Approach:

  • Take a variable and initialize it with the locals() function.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Take a variable and initialize it with the locals() function.
m = locals()
# Print the above result.
print(m)

Output:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f65e0415cc0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/29fd5ae710f8ed30944276be6a192e84.py', '__cached__': None, 'm': {...}}
Example-2: How does locals() function within a local scope?

Approach:

  • Create a function localNotExist() which returns the value returned  by locals() function.
  • Create another function localsExist().
  • Inside the localsExist take a variable and set its value to true.
  • Return the value returned by locals() function.
  • Inside the main function call localNotExist() function and print it.
  • call localsExist() function and print it.
  • The Exit of the Program.

Below is the implementation:

# Create a function localNotExist() which returns the value returned  by locals() function.


def localNotExist():
    return locals()
# Create another function localsExist().


def localsExist():
  # Inside the localsExist take a variable and set its value to true.
    present = True
    # Return the value returned by locals() function.

    return locals()


# Inside the main function call localNotExist() function and print it.
# call localsExist() function and print it.
print('localNotExist :', localNotExist())
print('localsExist :', localsExist())

Output:

localNotExist : {}
localsExist : {'present': True}

Fed up with searching various pages for the list of Python Built in Functions? Look at the tutorial linked here and explore all coding samples of built-in functions of python.

Python locals() Function with Examples Read More »

Python oct() Function with Examples

In the previous article, we have discussed Python min() Function with Examples
oct() Function in Python:

The oct() function is used to convert an integer to an octal string.

Python prefixes octal strings with 0o.

Syntax:

oct(number)

Parameters

number: This is required. It is an integer number.

If the value is not an integer (binary, decimal, or hexadecimal), it should implement __index__() to return an integer.

Return Value:

The oct() function takes an integer number and returns an octal string.

Examples:

Example1:

Input:

Given Number = 18

Output:

The given number's{ 18 } Octal Value =  0o22
The oct() function Return Type = <class 'str'>

Example2:

Input:

Given number  = 13
Given binary number  = 0b10
Given hexadecimal number  = 0XB

Output:

The oct(13) value is =  0o15
The oct(0b10) value =  0o2
The oct(0XB) value =  0o13

oct() Function with Examples in Python

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

Approach:

  • Give the number as static input and store it in a variable.
  • Pass the given number as an argument to the oct() function to get the Octal value of a given number.
  • Store it in another variable.
  • Print the given number’s OctalValue.
  • Print the Return Type of oct() Function using the type() method by passing the oct(given number) as an argument to it.
  • The Exit of the program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numbr = 18
# Pass the given number as an argument to the oct() function to get the
# Octal value of a given number.
# Store it in another variable.
Octal_valu = oct(gvn_numbr)
# Print the given number's Octal Value.
print("The given number's{", gvn_numbr,
      "} Octal Value = ", Octal_valu)
# Print the return Type of oct() Function using the type() method by passing
# the oct(given number) as an argument to it.
print("The oct() function Return Type =", type(oct(gvn_numbr)))

Output:

The given number's{ 18 } Octal Value =  0o22
The oct() function Return Type = <class 'str'>
oct() For binary and Hexadecimal numbers
# converting decimal to octal
print('The oct(13) value is = ', oct(13))

# converting binary to octal
print('The oct(0b10) value = ', oct(0b10))

# converting hexadecimal to octal
print('The oct(0XB) value = ', oct(0XB))

Output:

The oct(13) value is =  0o15
The oct(0b10) value =  0o2
The oct(0XB) value =  0o13

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

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Pass the given number as an argument to the oct() function to get the Octal value of a given number.
  • Store it in another variable.
  • Print the given number’s OctalValue.
  • Print the Return Type of oct() Function using the type() method by passing the oct(given number) as an argument to it.
  • The Exit of the program.

Below is the implementation:

# Give the number as user input using the int(input()) function and store it in a variable.
gvn_numbr = int(input("Enter some random number = "))
# Pass the given number as an argument to the oct() function to get the
# Octal value of a given number.
# Store it in another variable.
Octal_valu = oct(gvn_numbr)
# Print the given number's Octal Value.
print("The given number's{", gvn_numbr,
      "} Octal Value = ", Octal_valu)
# Print the return Type of oct() Function using the type() method by passing
# the oct(given number) as an argument to it.
print("The oct() function Return Type =", type(oct(gvn_numbr)))

Output:

Enter some random number = 10
The given number's{ 10 } Octal Value = 0o12
The oct() function Return Type = <class 'str'>

Fed up with searching various pages for the list of Python Built in Functions? Look at the tutorial linked here and explore all coding samples of built-in functions of python.

Python oct() Function with Examples Read More »

Python len() Function with Examples

In the previous article, we have discussed Python locals() Function with Examples
len() Function in Python:

The number of items in an object is returned by the len() function.

The len() function returns the number of characters in a string when the object is a string.

Syntax:

len(object)

Parameters

object: This is Required. It is an object. It should be a sequence or a collection.

Return Value:

The number of items in an object is returned by the len() function.

A TypeError exception will be thrown if an argument is not passed or if an invalid argument is passed.

Examples:

Example1:

Input:

Given List = [1, 20, 3, 40, 5]

Output:

The length of the given list =  5

Example2:

Input:

Given String = "hello btechgeeks"

Output:

The length of the given string =  16

len() Function with Examples in Python

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

1)For Lists

Approach:

  • Give the list as static input and store it in a variable.
  • Pass the given list as an argument to the len() function to get the length of the given list.
  • Store it in another variable.
  • Print the length of the given list.
  • The Exit of the program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = [1, 20, 3, 40, 5]
# Pass the given list as an argument to the len() function to get the length
# of the given list.
# Store it in another variable.
lst_lengt = len(gvn_lst)
# Print the length of the given list.
print("The length of the given list = ", lst_lengt)

Output:

The length of the given list =  5
2)For Strings

Approach:

  • Give the string as static input and store it in a variable.
  • Pass the given string as an argument to the len() function to get the length of the given string.
  • Store it in another variable.
  • Print the length of the given string.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "hello btechgeeks"
# Pass the given string as an argument to the len() function to get the length
# of the given string.
# Store it in another variable.
str_lengt = len(gvn_str)
# Print the length of the given string.
print("The length of the given string = ", str_lengt)

Output:

The length of the given string =  16
How does len() work with dictionaries and sets?
# set doesn't allows duplicates
gvn_set = {10, 20, 40, 50, 10}
print("The length of the given set", gvn_set, "=", len(gvn_set))

gvn_set2 = set()
print("The length of the given set", gvn_set2, "=", len(gvn_set2))

gvn_dictnry = {100: 'hello', 200: 'btechgeeks'}
print("The length of the given dictionary", gvn_dictnry, "=", len(gvn_dictnry))

Output:

The length of the given set {40, 10, 20, 50} = 4
The length of the given set set() = 0
The length of the given dictionary {100: 'hello', 200: 'btechgeeks'} = 2

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

1)For Lists

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Pass the given list as an argument to the len() function to get the length of the given list.
  • Store it in another variable.
  • Print the length of the given list.
  • The Exit of the 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()))
# Pass the given list as an argument to the len() function to get the length
# of the given list.
# Store it in another variable.
lst_lengt = len(gvn_lst)
# Print the length of the given list.
print("The length of the given list = ", lst_lengt)

Output:

Enter some random List Elements separated by spaces = -1 -2 7 8 9 0 3
The length of the given list = 7
2)For Strings

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Pass the given string as an argument to the len() function to get the length of the given string.
  • Store it in another variable.
  • Print the length of the given string.
  • The Exit of the program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Pass the given string as an argument to the len() function to get the length
# of the given string.
# Store it in another variable.
str_lengt = len(gvn_str)
# Print the length of the given string.
print("The length of the given string = ", str_lengt)

Output:

Enter some random string = good morning btechgeeks
The length of the given string = 23

Fed up with searching various pages for the list of Python Built in Functions? Look at the tutorial linked here and explore all coding samples of built-in functions of python.

Python len() Function with Examples Read More »

Python max() Function with Examples

In the previous article, we have discussed Python len() Function with Examples
max() Function in Python:

The max() function returns the item with the highest value or the highest value in an iterable.

If the values are strings, they are compared alphabetically.

Syntax:

max(iterable)

or

max(n1, n2, n3,........)

Parameters

iterable: An iterable that compares one or more items.

n1, n2, n3,……..: a single or multiple items to compare.

Return Value:

max() returns the iterable’s largest element.

Examples:

Example1:

Input:

Given List = [1, 2, 5, 6, 15, 7]

Output:

The greatest number in the given list = 15

Example2:

Input:

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

Output:

The largest string in the given list (alphabetically ordered) is :
this

Note:

If the items in an iterable are strings, the largest (alphabetically ordered) 
item is returned.

max() Function with Examples in Python

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

1)For Number List

Approach:

  • Give the list as static input and store it in a variable.
  • Pass the given list as an argument to the max() function to get the greatest or the largest element in the given list.
  • Store it in another variable.
  • Print the greatest element(number) in the given list.
  • The Exit of the program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = [1, 2, 5, 6, 15, 7]
# Pass the given list as an argument to the max() function to get the greatest
# or the largest element in the given list.
# Store it in another variable.
greatst_numb = max(gvn_lst)
# Print the greatest element(number) in the given list.
print("The greatest number in the given list =", greatst_numb)

Output:

The greatest number in the given list = 15
2)For String List

Similarly, do the same to get the largest string in the given list.

Note: If the items in an iterable are strings, the largest (alphabetically ordered) item is returned.

Approach:

  • Give the list (string list)as static input and store it in a variable.
  • Pass the given list as an argument to the max() function to get the largest string in the given list. If the items in an iterable are strings, the largest (alphabetically ordered) item is returned.
  • Store it in another variable.
  • Print the largest string in the given list (alphabetically ordered).
  • The Exit of the program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_strlst = ["hello", "this", "is", "btechgeeks"]
# Pass the given list as an argument to the max() function to get the largest
# string in the given list.If the items in an iterable are strings,
# the largest (alphabetically ordered) item is returned.
# Store it in another variable.
largst_str = max(gvn_strlst)
# Print the largest string in the given list (alphabetically ordered).
print("The largest string in the given list (alphabetically ordered) is :")
print(largst_str)

Output:

The largest string in the given list (alphabetically ordered) is :
this
3)Passing multiple arguments

To get the greatest number from the given numbers.

# Give some random numbers as arguments to the max() function.
largst_numb = max(5, 10, -2, 9, 6)
# Print the greatest number from the given numbers
print("The greatest number from the given numbers = ", largst_numb)

Output:

The greatest number from the given numbers =  10

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

1)For Number List

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Pass the given list as an argument to the max() function to get the greatest or the largest element in the given list.
  • Store it in another variable.
  • Print the greatest element(number) in the given list.
  • The Exit of the 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()))
# Pass the given list as an argument to the max() function to get the greatest
# or the largest element in the given list.
# Store it in another variable.
greatst_numb = max(gvn_lst)
# Print the greatest element(number) in the given list.
print("The greatest number in the given list =", greatst_numb)

Output:

Enter some random List Elements separated by spaces = 34 50 68 12 100
The greatest number in the given list = 100
2)For String List

Approach:

  • Give the list (string list) as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Pass the given list as an argument to the max() function to get the largest string in the given list. If the items in an iterable are strings, the largest (alphabetically ordered) item is returned.
  • Store it in another variable.
  • Print the largest string in the given list (alphabetically ordered).
  • The Exit of the program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_strlst = list(input(
   'Enter some random List Elements separated by spaces = ').split())
# Pass the given list as an argument to the max() function to get the largest
# string in the given list.If the items in an iterable are strings,
# the largest (alphabetically ordered) item is returned.
# Store it in another variable.
largst_str = max(gvn_strlst)
# Print the largest string in the given list (alphabetically ordered).
print("The largest string in the given list (alphabetically ordered) is :")
print(largst_str)

Output:

Enter some random List Elements separated by spaces = good morning btechgeeks
The largest string in the given list (alphabetically ordered) is :
morning

Fed up with searching various pages for the list of Python Built in Functions? Look at the tutorial linked here and explore all coding samples of built-in functions of python.

Python max() Function with Examples Read More »

Python hasattr() Method with Examples

In the previous article, we have discussed Python globals() Function with Examples
hasattr() Method in Python:

If the specified object has the specified attribute, the hasattr() function returns true; otherwise, it returns False.

Syntax:

hasattr(object, attribute)

Parameter Values

object: This is required. It is an object.

attribute: The name of the attribute to be checked whether exists or not.

Return Value:

The method hasattr() returns:

  • True if the object has the specified named attribute.
  • False if the object lacks the specified named attribute.

hasattr() Method with Examples in Python

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

Approach:

  • Create a class say Employdetails.
  • Take a variable and initialize it with some random number(id).
  • Take another variable and initialize it with some random name(ename).
  • Create an object for the class and store it in a variable.
  • Check if the above class has an attribute id by passing arguments like the above object and attribute name using the hasattr() function and print the result.
  • Similarly, do the same for the other attribute(jobrole) and print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a class say Employdetails.
class Employdetails:
    # Take a variable and initialize it with some random number(id).
    id = 10
    # Take another variable and initialize it with some random name(ename).
    ename = 'Hitler'


# Create an object for the class and store it in a variable.
Employdetailsobj = Employdetails()
# Check if the above class has an attribute id by passing arguments like the
# above object and attribute name using the hasattr() function and print the result.
print('Does Employdetails has id?:', hasattr(Employdetailsobj, 'id'))
# Similarly, do the same for the other attribute(jobrole) and print the result.
print('Does Employdetails has jobrole?:', hasattr(Employdetailsobj, 'jobrole'))

Output:

Does Employdetails has id?: True
Does Employdetails has jobrole?: False

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

Approach:

  • Create a class say Employdetails.
  • Take a variable and initialize it with some random number(id).
  • Take another variable and initialize it with some random name(ename).
  • Create an object for the class and store it in a variable.
  • Give some random attribute name as user input using the input() function and store it in a variable.
  • Give the other attribute name as user input using the input() function and store it in another variable.
  • Check if the above class has the above attribute by passing arguments like the above object and above attribute name using the hasattr() function and print the result.
  • Similarly, do the same for the other attribute and print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a class say Employdetails.
class Employdetails:
    # Take a variable and initialize it with some random number(id).
    id = 10
    # Take another variable and initialize it with some random name(ename).
    ename = 'Hitler'


# Create an object for the class and store it in a variable.
Employdetailsobj = Employdetails()
# Give some random attribute name as user input using the input() function
# and store it in a variable.
atrname1 = input("Enter some random attribute name = ")
# Give the other attribute name as user input using the input() function
# and store it in another variable.
atrname2 = input("Enter some random attribute name = ")
# Check if the above class has the above attribute by passing arguments like the above object
# and above attribute name using the hasattr() function and print the result.
print('Does Employdetails has', atrname1, '?:',
      hasattr(Employdetailsobj, atrname1))
# Similarly, do the same for the other attribute and print the result.
print('Does Employdetails has', atrname2, '?:',
      hasattr(Employdetailsobj, atrname2))

Output:

Enter some random attribute name = age
Enter some random attribute name = ename
Does Employdetails has age ?: False
Does Employdetails has ename ?: True

Fed up with searching various pages for the list of Python Built in Functions? Look at the tutorial linked here and explore all coding samples of built-in functions of python.

Python hasattr() Method with Examples Read More »

Python globals() Function with Examples

In the previous article, we have discussed Python filter() Function with Examples
globals() Function in Python:

The globals() function returns a dictionary containing the global symbol table.

A symbol table contains information about the current program that is required.

Variable names, methods, classes, and so on are examples of this.

There are two types of symbol tables.

  1. Local symbol Table
  2. Global symbol Table

The local symbol table stores all information related to the program’s local scope and is accessed in Python via the locals() method.

The local scope could be within a function, a class, or something else.

Similarly, a Global symbol table stores all information related to the program’s global scope and is accessed in Python via the globals() method.

All functions and variables that are not associated with any class or function are included in the global scope.

Syntax:

globals()

Parameter Values: The globals() method does not accept any parameters.

Return Value:

This method returns the dictionary containing the current global symbol table.

globals() Function with Examples in Python

1)Using global variables, make changes to global variables ()

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

Approach:

  • Give the number(id) as static input and store it in a variable.
  • Modify the given number to some random number by using the globals() function.
  • Print the new number after modification.
  • The Exit of the Program.

Below is the implementation:

# Give the number(id) as static input and store it in a variable.
gvn_id = 10
# Modify the given number to some random number by using the globals() function.
globals()['gvn_id'] = 5
# Print the new number after modification.
print('The modified Id is:', gvn_id)

Output:

The modified Id is: 5
How does Python’s globals() method work?

Below is the implementation:

# Take a variable and initialize it with the globals() function.
m = globals()
# Print the above result.
print(m)

Output:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f0e651f0cc0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/78f96300568d7239be1e5414d328ce86.py', '__cached__': None, 'm': {...}}

All global variables and other symbols for the current program are displayed in the output.

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

Approach:

  • Give the number(id) as user input using the int(input()) function and store it in a variable.
  • Give the new number as user input using the int(input()) function and store it in another variable.
  • Modify the given number to the above given new number by using the globals() function.
  • Print the new number after modification.
  • The Exit of the Program.

Below is the implementation:

# Give the number(id) as user input using the int(input()) function and store it in a variable.
gvn_id = int(input("Enter some random number = "))
# Give the new number as user input using the int(input()) function and store it in another variable.
new_id = int(input("Enter some random number = "))
# Modify the given number to the above given new number by using the globals() function.
globals()['gvn_id'] = new_id
# Print the new number after modification.
print('The modified Id is:', gvn_id)

Output:

Enter some random number = 20
Enter some random number = 50
The modified Id is: 50

Fed up with searching various pages for the list of Python Built in Functions? Look at the tutorial linked here and explore all coding samples of built-in functions of python.

 

Python globals() Function with Examples Read More »

Python filter() Function with Examples

In the previous article, we have discussed Python enumerate() Function with Examples
filter() Function in Python:

The filter() function returns an iterator in which the items are filtered through a function to determine whether or not the item is accepted.

Syntax:

filter(function, iterable)

Parameter Values:

function: It is a function that will be executed for each item in the iterable.

iterable: The iterable that will be filtered.

Return Value:

The iterator is returned by the filter() function.

Examples:

Example1:

Input:

Given List = [3, 10, 12, 13, 20, 7, 1, 16]

Output:

The Even numbers in a given list :
10
12
20
16

Example2:

Input:

Given List = [4, 6, 7, 9, 10, 12, 11]

Output:

The Even numbers in a given list :
4
6
10
12

filter() Function 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.
  • Create a function say Even_numbers which accepts a number as an argument and returns true if the argument is an even number else it returns false.
  • Check if the given number is even using the if conditional statement.
  • If it is true, then return True.
  • Else return False.
  • Pass the above Function(Even_numbers),  given list as arguments to the filter function that returns an iterator in which the items are filtered through a function to determine whether or not the item is accepted.
  • Store it in another variable.
  • Loop in the above result using the for loop.
  • Print the iterator value of the for loop.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = [3, 10, 12, 13, 20, 7, 1, 16]

# Create a function say Even_numbers which accepts a number as an argument and returns
# true if the argument is even number else it returns false.


def Even_numbers(numb):
  # Check if the given number is even using the if conditional statement.
    if numb % 2 == 0:
      # If it is true, then return True.
        return True
    # Else return False.
    else:
        return False


# Pass the above Function(Even_numbers),
# given list as arguments to the filter function that
# returns an iterator in which the items are filtered
# through a function to determine whether or not the item is accepted.
# Store it in another variable.
evn_numbrs = filter(Even_numbers, gvn_lst)
print("The Even numbers in a given list :")
# Loop in the above result using the for loop.
for n in evn_numbrs:
  # Print the iterator value of the for loop.
    print(n)

Output:

The Even numbers in a given list :
10
12
20
16
Using the Lambda Function Within a filter ()
gvn_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# The lambda function returns True for odd numbers
oddnumbrs_itrtor = filter(lambda n: (n % 2 != 0), gvn_lst)

# converting to list
odd_numbrs = list(oddnumbrs_itrtor)
print("The Odd numbers in a given list:")
print(odd_numbrs)

Output:

The Odd numbers in a given list:
[1, 3, 5, 7, 9]

Inside the filter, we have directly passed a lambda function ().

For Odd numbers, our lambda function returns True. As a result, the filter() function returns an iterator that only contains Odd numbers.

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

Approach:

  • Give the list as user input using map(),list(),input(),int() functions and store it in a variable.
  • Create a function say Even_numbers which accepts a number as an argument and returns true if the argument is an even number else it returns false.
  • Check if the given number is even using the if conditional statement.
  • If it is true, then return True.
  • Else return False.
  • Pass the above Function(Even_numbers),  given list as arguments to the filter function that returns an iterator in which the items are filtered through a function to determine whether or not the item is accepted.
  • Store it in another variable.
  • Loop in the above result using the for loop.
  • Print the iterator value of the for loop.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),int(),split() and map() functions
# and store it in a variable.
gvn_lst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))

# Create a function say Even_numbers which accepts a number as an argument and returns
# true if the argument is even number else it returns false.


def Even_numbers(numb):
  # Check if the given number is even using the if conditional statement.
    if numb % 2 == 0:
      # If it is true, then return True.
        return True
    # Else return False.
    else:
        return False


# Pass the above Function(Even_numbers),
# given list as arguments to the filter function that
# returns an iterator in which the items are filtered
# through a function to determine whether or not the item is accepted.
# Store it in another variable.
evn_numbrs = filter(Even_numbers, gvn_lst)
print("The Even numbers in a given list :")
# Loop in the above result using the for loop.
for n in evn_numbrs:
  # Print the iterator value of the for loop.
    print(n)

Output:

Enter some random List Elements separated by spaces = 4 6 7 9 10 12 11
The Even numbers in a given list :
4
6
10
12

Fed up with searching various pages for the list of Python Built in Functions? Look at the tutorial linked here and explore all coding samples of built-in functions of python.

Python filter() Function with Examples Read More »

Python enumerate() Function with Examples

In the previous article, we have discussed Python divmod() Method with Examples
enumerate() Function in Python:

The enumerate() function accepts a collection (for example, a tuple) and returns an enumerate object.

The enumerate() function adds a counter as the enumerate object’s key.

Syntax:

enumerate(iterable, start)

Parameter Values

iterable: It is an iterable object.

start: This is optional. It is a number. Specifying the enumerate object’s starting number. 0 is the default.

Return Value:

The method enumerate() adds a counter to an iterable and returns it. The object returned is an enumerate object.

Enumerate objects can be converted to list and tuple using the list() and tuple() methods, respectively.

Examples:

Example1:

Input:

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

Output:

The given list after applying enumerate() function :
[(0, 'hello'), (1, 'this'), (2, 'is'), (3, 'btechgeeks')]

Example2:

Input:

Given List = ['good', 'morning', 'btechgeeks']
Given start value = 5

Output:

The given list after applying enumerate() function from the given start :
[(5, 'good'), (6, 'morning'), (7, 'btechgeeks')]

enumerate() Function with Examples in Python

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

1)Without giving start value

Approach:

  • Give the list as static input and store it in a variable.
  • Pass the given list to the enumerate() function as an argument that returns an enumerate object. The enumerate() function adds a counter as the enumerate object’s key.
  • Store it in another variable.
  • Convert the above result to a list using the list() function and print the result.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ['hello', 'this', 'is', 'btechgeeks']
# Pass the given list to the enumerate() function as an argument that returns
# an enumerate object. The enumerate() function adds a counter as the
# enumerate object's key.
# Store it in another variable.
enumerte_lst = enumerate(gvn_lst)
print("The given list after applying enumerate() function :")
# Convert the above result to a list using the list() function and print the result.
print(list(enumerte_lst))

Output:

The given list after applying enumerate() function :
[(0, 'hello'), (1, 'this'), (2, 'is'), (3, 'btechgeeks')]
2)With giving start value

Approach:

  • Give the list as static input and store it in a variable.
  • Give the number(start value) as static input and store it in another variable.
  • Pass the given list, start value to the enumerate() function as arguments that returns an enumerate object from the given start value. The enumerate() function adds a counter as the enumerate object’s key.
  • Store it in another variable.
  • Convert the above result to a list using the list() function and print the result.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ['good', 'morning', 'btechgeeks']
# Give the number(start value) as static input and store it in another variable.
gvn_strt = 5
# Pass the given list, start value to the enumerate() function as the arguments
# that returns an enumerate object from the given start value. The enumerate()
# function adds a counter as the enumerate object's key.
# Store it in another variable.
enumerte_lst = enumerate(gvn_lst, gvn_strt)
print("The given list after applying enumerate() function from the given start :")
# Convert the above result to a list using the list() function and print the result.
print(list(enumerte_lst))

Output:

The given list after applying enumerate() function from the given start :
[(5, 'good'), (6, 'morning'), (7, 'btechgeeks')]

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

Approach:

  • Give the list as user input using list(),int(),split() and map() functions and store it in a variable.
  • Pass the given list to the enumerate() function as an argument that returns an enumerate object. The enumerate() function adds a counter as the enumerate object’s key.
  • Store it in another variable.
  • Convert the above result to a list using the list() function and print the result.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),int(),split() and map() functions
# and store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Pass the given list to the enumerate() function as an argument that returns
# an enumerate object. The enumerate() function adds a counter as the
# enumerate object's key.
# Store it in another variable.
enumerte_lst = enumerate(gvn_lst)
print("The given list after applying enumerate() function :")
# Convert the above result to a list using the list() function and print the result.
print(list(enumerte_lst))

Output:

Enter some random List Elements separated by spaces = 1000 2000 3000 4000
The given list after applying enumerate() function :
[(0, 1000), (1, 2000), (2, 3000), (3, 4000)]
2)With giving start value

Approach:

  • Give the list as user input using list(),int(),split() and map() functions and store it in a variable.
  • Give the number(start value) as user input using the int(input()) function and store it in another variable.
  • Pass the given list, start value to the enumerate() function as arguments that returns an enumerate object from the given start value. The enumerate() function adds a counter as the enumerate object’s key.
  • Store it in another variable.
  • Convert the above result to a list using the list() function and print the result.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),int(),split() and map() functions
# and store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Give the number(start value) as user input using the int(input()) function 
# and store it in another variable.
gvn_strt = int(input("Enter some random number = "))
# Pass the given list, start value to the enumerate() function as the arguments
# that returns an enumerate object from the given start value. The enumerate()
# function adds a counter as the enumerate object's key.
# Store it in another variable.
enumerte_lst = enumerate(gvn_lst, gvn_strt)
print("The given list after applying enumerate() function from the given start :")
# Convert the above result to a list using the list() function and print the result.
print(list(enumerte_lst))

Output:

Enter some random List Elements separated by spaces = 1 2 3 4 5
Enter some random number = 100
The given list after applying enumerate() function from the given start :
[(100, 1), (101, 2), (102, 3), (103, 4), (104, 5)]

Fed up with searching various pages for the list of Python Built in Functions? Look at the tutorial linked here and explore all coding samples of built-in functions of python.

Python enumerate() Function with Examples Read More »