Author name: Vikram Chiluka

Python Random randint() Method with Examples

Random randint() Method in Python:

The randint() method returns an integer number representing a randomly chosen element from the specified range.

Note: It is to be noted that randint() method is an alias for randrange(start, stop+1).

Syntax:

random.randint(start, stop)

Parameters

start: This is Required. It is an integer indicating the starting position.

stop: This is Required. It is an integer indicating the position at which to end.

Examples:

Example1:

Input:

Given start value = 4
Given stop value = 12

Output:

The random number between 4 and 12 = 12  (includes both 4 and 12)

Example2:

Input:

Given start value = 40
Given stop value = 45

Output:

The random number between 40 and 45 = 42 (includes both 40 and 45)

Random randint() Method with Examples in Python

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

Approach:

  • Import random module using the import keyword.
  • Give the number(start value) as static input and store it in a variable.
  • Give the other number(stop value) as static input and store it in another variable.
  • Pass the given start and stop values as the arguments to the random.randint() method to get a random number between the given start and stop values ( both start and stop values are included).
  • Store it in another variable.
  • Print a random number between the given start and stop values.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number(start value) as static input and store it in a variable.
gvn_strtval = 4
# Give the other number(stop value) as static input and store it in another variable.
gvn_stopval = 12
# Pass the given start and stop values as the arguments to the random.randint()
# method to get a random number between the given start and stop values.
# ( both start and stop values are included).
# Store it in another variable.
rslt = random.randint(gvn_strtval, gvn_stopval)
# Print a random number between the given start and stop values.
print("The random number between", gvn_strtval, "and", gvn_stopval, "=", rslt)

Output:

The random number between 4 and 12 = 12

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

Approach:

  • Import random module using the import keyword.
  • Give the number(start value) as user input using the int(input()) function and store it in a variable.
  • Give the other number(stop value)  as user input using the int(input()) function and store it in another variable.
  • Pass the given start and stop values as the arguments to the random.randint() method to get a random number between the given start and stop values ( both start and stop values are included).
  • Store it in another variable.
  • Print a random number between the given start and stop values.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number(start value) as user input using the int(input()) function and store it in a variable.
gvn_strtval = int(input("Enter some random number = "))
# Give the other number(stop value)  as user input using the int(input()) function 
# and store it in another variable.
gvn_stopval = int(input("Enter some random number = "))
# Pass the given start and stop values as the arguments to the random.randint()
# method to get a random number between the given start and stop values.
# ( both start and stop values are included).
# Store it in another variable.
rslt = random.randint(gvn_strtval, gvn_stopval)
# Print a random number between the given start and stop values.
print("The random number between", gvn_strtval, "and", gvn_stopval, "=", rslt)

Output:

Enter some random number = 40
Enter some random number = 45
The random number between 40 and 45 = 42

Python Random randint() Method with Examples Read More »

Python Random choice() Method with Examples

Random choice() Method in Python:

The choice() method selects an element at random from the specified sequence and returns it.

The sequence could be a string, a range, a list, a tuple, or anything else.

Syntax:

random.choice(sequence)

Parameters

sequence: This is Required. It could be a list, a tuple, a range of numbers, and so on.

Examples:

Example1:

Input:

Given list = [4, 7, 9, 0, 1]

Output:

The random element from a given list =  7

Example2:

Input:

Given string = "hello"

Output:

The random character from a given string =  e

Random choice() Method with Examples in Python

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

Approach:

  • Import random module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Pass the given list as an argument to the random.choice() method to get a random element from a given list.
  • Store it in another variable.
  • Print a random element from a given list.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the list as static input and store it in a variable.
gvn_lst = [4, 7, 9, 0, 1]
# Pass the given list as an argument to the random.choice() method to get a
# random element from a given list.
# Store it in another variable.
rslt = random.choice(gvn_lst)
# Print a random element from a given list.
print("The random element from a given list = ", rslt)

Output:

The random element from a given list =  7
For Strings

Approach:

  • Import random module using the import keyword.
  • Give the string as static input and store it in a variable.
  • Pass the given string as an argument to the random.choice() method to get a random character from a given string.
  • Store it in another variable.
  • Print a random character from a given string.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the string as static input and store it in a variable.
gvn_str = "hello"
# Pass the given string as an argument to the random.choice() method to get a
# random character from a given string.
# Store it in another variable.
rslt = random.choice(gvn_str)
# Print a random character from a given string.
print("The random character from a given string = ", rslt)

Output:

The random character from a given string =  e

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

Approach:

  • Import random module using the import keyword.
  • 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 random.choice() method to get a random element from a given list.
  • Store it in another variable.
  • Print a random element from a given list.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# 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 random.choice() method to get a
# random element from a given list.
# Store it in another variable.
rslt = random.choice(gvn_lst)
# Print a random element from a given list.
print("The random element from a given list = ", rslt)

Output:

Enter some random List Elements separated by spaces = 10 20 30 60 80
The random element from a given list = 10
For Strings

Approach:

  • Import random module using the import keyword.
  • 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 random.choice() method to get a random character from a given string.
  • Store it in another variable.
  • Print a random character from a given string.
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# 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 random.choice() method to get a
# random character from a given string.
# Store it in another variable.
rslt = random.choice(gvn_str)
# Print a random character from a given string.
print("The random character from a given string = ", rslt)

Output:

Enter some random string = btechgeeks
The random character from a given string = k

Python Random choice() Method with Examples Read More »

Python Random sample() Method with Examples

Random sample() Method in Python:

The sample() method returns a list containing a randomly selected number of items from a sequence.

Note: Please keep in mind that this method does not alter(change) the original sequence.

Syntax:

random.sample(sequence, size)

Parameters

sequence: This is Required. It could be any sequence like a list, a tuple, a range of numbers, and so on.

size: This is Required. The number of items in the returned list.

Examples:

Example1:

Input:

Given list = [4, 7, 9, 0, 1]
Given size = 3

Output:

The 3 random items from a given list =  [1, 9, 7]

Example2:

Input:

Given list = ["hello", "this", "is", "btechgeeks"]
Given size = 2

Output:

The 2 random items from a given list =  ['is', 'btechgeeks']

Random sample() Method with Examples in Python

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

Approach:

  • Import random module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Give the size of the list to be returned as static input and store it in another variable.
  • Pass the given list, size as the arguments to the random.sample() method to get the given number(size) of random items from a given list
  • Store it in another variable.
  • Print the given number of random items from a given list
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the list as static input and store it in a variable.
gvn_lst = [4, 7, 9, 0, 1]
# Give the size of the list to be returned as static input and store it in
# another variable.
gvn_size = 3
# Pass the given list, size as the arguments to the random.sample() method to
# get the given number(size) of random items from a given list
# Store it in another variable.
rslt = random.sample(gvn_lst, gvn_size)
# Print the given number of random items from a given list
print("The", gvn_size, "random items from a given list = ", rslt)

Output:

The 3 random items from a given list =  [1, 9, 7]

Note: Similarly, you can also try for strings, to get the given number of random characters from a given string.

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

Approach:

  • Import random module using the import keyword.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the size of the list to be returned as user input using the int(input()) function and store it in another variable.
  • Pass the given list, size as the arguments to the random.sample() method to get the given number(size) of random items from a given list
  • Store it in another variable.
  • Print the given number of random items from a given list
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# 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 size of the list to be returned as user input using the int(input())
# function and store it in another variable.
gvn_size = int(input("Enter some random number = "))
# Pass the given list, size as the arguments to the random.sample() method to
# get the given number(size) of random items from a given list
# Store it in another variable.
rslt = random.sample(gvn_lst, gvn_size)
# Print the given number of random items from a given list
print("The", gvn_size, "random items from a given list = ", rslt)

Output:

Enter some random List Elements separated by spaces = 23 10 20 30 40 50
Enter some random number = 2
The 2 random items from a given list = [50, 20]

Python Random sample() Method with Examples Read More »

Python Itertools.accumulate() Function with Examples

Itertools Module:

The Python itertools module is a collection of tools for working with iterators.

Iterators are simply data types that can be used in a for loop. The list is the most commonly used iterator in Python.

Requirements for using itertools

Before using, the itertools module must be imported. Because we want to work with operators, we must also import the operator module.

The Itertools module is a collection of functions.

Itertools.accumulate() Function:

This iterator accepts two arguments:

the iterable target and the function to be followed at each iteration of value in target. If no function is specified, addition is performed by default. If the input iterable is empty, so will the output iterable.

This function generates an iterator that iterates through the results of a function.

Syntax:

itertools.accumulate(iterable[, func])

Parameter Values

iterable: This is Required. Elements to be gathered or accumulated

function: This is Optional. Iterables are accumulated using this function.

Examples:

Example1:

Input:

Given List = [4, 2, 1, 5, 3]

Output:

The cumulative of the given list = [4, 6, 7, 12, 15]

Example2:

Input:

Given List = [2, 3, 4, 1, 5]
Given function = lambda a, b: a*b

Output:

[2, 6, 24, 24, 120]

Itertools.accumulate() Function with Examples in Python

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

Approach:

  • Import itertools module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Pass the given list as an argument to the itertools.accumulate() method that calculates cumulative sum of the given list.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in a variable.
  • Print the cumulative of the given list.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the list as static input and store it in a variable.
gvn_lst = [4, 2, 1, 5, 3]
# Pass the given list as an argument to the itertools.accumulate() method that
# calculates cumulative sum of the given list.
# Store it in another variable.
rslt = itertools.accumulate(gvn_lst)
# Convert the above result into a list using the list() function and store
# it in a variable.
rslt_lst = list(rslt)
# Print the cumulative of the given list.
print("The cumulative of the given list =", rslt_lst)

Output:

The cumulative of the given list = [4, 6, 7, 12, 15]

with passing the iterable, function as parameters

import itertools
gvn_lst = [2, 3, 4, 1, 5]
rslt = itertools.accumulate(gvn_lst, lambda a, b: a*b)
print(list(rslt))

Output:

[2, 6, 24, 24, 120]

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

Approach:

  • Import itertools module using the import keyword.
  • 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 itertools.accumulate() method that calculates cumulative sum of the given list.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in a variable.
  • Print the cumulative of the given list.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools

# 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 itertools.accumulate() method that
# calculates cumulative sum of the given list.
# Store it in another variable.
rslt = itertools.accumulate(gvn_lst)
# Convert the above result into a list using the list() function and store
# it in a variable.
rslt_lst = list(rslt)
# Print the cumulative of the given list.
print("The cumulative of the given list =", rslt_lst)

Output:

Enter some random List Elements separated by spaces = 10 50 20 30 10
The cumulative of the given list = [10, 60, 80, 110, 120]

 

Python Itertools.accumulate() Function with Examples Read More »

Python Itertools.chain() Function with Examples

Itertools Module:

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings. Chain is one such itertools function ().

Itertools.chain() Function:

It’s a function that takes a list of iterables and returns a single iterable. It combines all of the iterables and returns a single iterable as output. Its output cannot be directly used and must thus be explicitly converted into iterables. This function belongs to the iterators terminating iterators category.

Syntax:

chain (*iterables)

Examples:

Example1:

Input:

Given first List = [9, 8, 7, 6]
Given second List = [40, 30, 20, 10]

Output:

The result after chaining the given two lists:
[9, 8, 7, 6, 40, 30, 20, 10]

Explanation:

Here the chain() function combines the given first and second list and
returns a new list[9, 8, 7, 6, 40, 30, 20, 10]

Example2:

Input:

Given first string = "hello"
Given second string = "ALL"

Output:

The result after chaining the given two strings:
['h', 'e', 'l', 'l', 'o', 'A', 'L', 'L']

Itertools.chain() Function with Examples in Python

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

Approach:

  • Import itertools module using the import keyword.
  • Give the first list as static input and store it in a variable.
  • Give the second list as static input and store it in another variable.
  • Pass the given first and second lists as the arguments to the itertools.chain() method that combines(chains) the given two lists.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in a variable.
  • Print the result after chaining the given two lists.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the first list as static input and store it in a variable.
fst_lst = [9, 8, 7, 6]
# Give the second list as static input and store it in another variable.
scnd_lst = [40, 30, 20, 10]
# Pass the given first and second lists as the arguments to the itertools.chain()
# method that combines(chains) the given two lists.
# Store it in another variable.
rslt_chain = itertools.chain(fst_lst, scnd_lst)
# Convert the above result into a list using the list() function and store it
# in a variable.
rslt_lst = list(rslt_chain)
# Print the result after chaining the given two lists.
print("The result after chaining the given two lists:")
print(rslt_lst)

Output:

The result after chaining the given two lists:
[9, 8, 7, 6, 40, 30, 20, 10]

For Strings

Approach:

  • Import itertools module using the import keyword.
  • Give the first string as static input and store it in a variable.
  • Give the second string as static input and store it in another variable.
  • Pass the given first and second strings as the arguments to the itertools.chain() method that combines(chains) the given two strings.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in a variable.
  • Print the result after chaining the given two strings.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the first string as static input and store it in a variable.
fst_str = "hello"
# Give the second string as static input and store it in another variable.
scnd_str = "ALL"
# Pass the given first and second strings as the arguments to the itertools.chain()
# method that combines(chains) the given two strings.
# Store it in another variable.
rslt_chain = itertools.chain(fst_str, scnd_str)
# Convert the above result into a list using the list() function and store it
# in a variable.
rslt_lst = list(rslt_chain)
# Print the result after chaining the given two strings.
print("The result after chaining the given two strings:")
print(rslt_lst)

Output:

The result after chaining the given two strings:
['h', 'e', 'l', 'l', 'o', 'A', 'L', 'L']

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

Approach:

  • Import itertools module using the import keyword.
  • Give the first list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the second list as user input using list(),map(),input(),and split() functions.
  • Store it in another variable.
  • Pass the given first and second lists as the arguments to the itertools.chain() method that combines(chains) the given two lists.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in a variable.
  • Print the result after chaining the given two lists.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the first list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
fst_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Give the second list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
scnd_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
   
# Pass the given first and second lists as the arguments to the itertools.chain()
# method that combines(chains) the given two lists.
# Store it in another variable.
rslt_chain = itertools.chain(fst_lst, scnd_lst)
# Convert the above result into a list using the list() function and store it
# in a variable.
rslt_lst = list(rslt_chain)
# Print the result after chaining the given two lists.
print("The result after chaining the given two lists:")
print(rslt_lst)

Output:

Enter some random List Elements separated by spaces = 10 15 20
Enter some random List Elements separated by spaces = 100 200 300
The result after chaining the given two lists:
[10, 15, 20, 100, 200, 300]

For Strings

Approach:

  • Import itertools module using the import keyword.
  • Give the first string as user input using the input() function and store it in a variable.
  • Give the second string as user input using the input() function and store it in another variable.
  • Pass the given first and second strings as the arguments to the itertools.chain() method that combines(chains) the given two strings.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in a variable.
  • Print the result after chaining the given two strings.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the first string as user input using the input() function and store it in a variable.
fst_str = input("Enter some random string = ")
# Give the second string as user input using the input() function and 
# store it in another variable.
scnd_str = input("Enter some random string = ")
# Pass the given first and second strings as the arguments to the itertools.chain()
# method that combines(chains) the given two strings.
# Store it in another variable.
rslt_chain = itertools.chain(fst_str, scnd_str)
# Convert the above result into a list using the list() function and store it
# in a variable.
rslt_lst = list(rslt_chain)
# Print the result after chaining the given two strings.
print("The result after chaining the given two strings:")
print(rslt_lst)

Output:

Enter some random string = good
Enter some random string = morning
The result after chaining the given two strings:
['g', 'o', 'o', 'd', 'm', 'o', 'r', 'n', 'i', 'n', 'g']

Python Itertools.chain() Function with Examples Read More »

Python Itertools.chain.from_iterable() Function with Examples

Itertools Module:

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings.

Itertools.chain.from_iterable() Function:

chain.from_iterable() belongs to the category of terminating iterators. This function takes a single iterable as an argument, and all of the elements of the input iterable must also be iterable, and it returns a flattened iterable containing all of the input iterable’s elements.

Syntax:

chain.from_iterable(iterable)

Parameters

iterable: It could be any iterable like list, string, and so on.

Examples:

Example1:

Input:

Given List = ["good", "morning", "all"]

Output:

The flattened list of the given list:
['g', 'o', 'o', 'd', 'm', 'o', 'r', 'n', 'i', 'n', 'g', 'a', 'l', 'l']

Example2:

Input:

Given List = ["hello", ['a', 'l', 'l']]

Output:

The flattened list of the given list:
['h', 'e', 'l', 'l', 'o', 'a', 'l', 'l']

Itertools.chain.from_iterable() Function with Examples in Python

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

Approach:

  • Import itertools module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Pass the given list as an argument to the itertools.chain.from_iterable() function that returns a flattened list (list of characters) containing all of the given list elements.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in a variable.
  • Print the flattened list of the given list.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Give the list as static input and store it in a variable.
gvn_lst = ["good", "morning", "all"]
# Pass the given list as an argument to the itertools.chain.from_iterable()
# function that returns a flattened list (list of characters) containing all
# of the given list elements.
# Store it in another variable.
rslt_chain = itertools.chain.from_iterable(gvn_lst)
# Convert the above result into a list using the list() function and store it
# in a variable.
rslt_lst = list(rslt_chain)
# Print the flattened list of the given list.
print("The flattened list of the given list:")
print(rslt_lst)

Output:

The flattened list of the given list:
['g', 'o', 'o', 'd', 'm', 'o', 'r', 'n', 'i', 'n', 'g', 'a', 'l', 'l']
string and List as one input at a time
# Import itertools module using the import keyword.
import itertools
# Give the list as static input and store it in a variable.
gvn_lst = ["hello", ['a', 'l', 'l']]
# Pass the given list as an argument to the itertools.chain.from_iterable()
# function that returns a flattened list (list of characters) containing all
# of the given list elements.
# Store it in another variable.
rslt_chain = itertools.chain.from_iterable(gvn_lst)
# Convert the above result into a list using the list() function and store it
# in a variable.
rslt_lst = list(rslt_chain)
# Print the flattened list of the given list.
print("The flattened list of the given list:")
print(rslt_lst)

Output:

The flattened list of the given list:
['h', 'e', 'l', 'l', 'o', 'a', 'l', 'l']

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

Approach:

  • Import itertools module using the import keyword.
  • Give the list as user input using list(), input(),and split() functions.
  • Store it in a variable.
  • Pass the given list as an argument to the itertools.chain.from_iterable() function that returns a flattened list (list of characters) containing all of the given list elements.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in a variable.
  • Print the flattened list of the given list.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# 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())

# Pass the given list as an argument to the itertools.chain.from_iterable()
# function that returns a flattened list (list of characters) containing all
# of the given list elements.
# Store it in another variable.
rslt_chain = itertools.chain.from_iterable(gvn_lst)
# Convert the above result into a list using the list() function and store it
# in a variable.
rslt_lst = list(rslt_chain)
# Print the flattened list of the given list.
print("The flattened list of the given list:")
print(rslt_lst)

Output:

Enter some random List Elements separated by spaces = python code
The flattened list of the given list:
['p', 'y', 't', 'h', 'o', 'n', 'c', 'o', 'd', 'e']

Python Itertools.chain.from_iterable() Function with Examples Read More »

Python Itertools.compress() Function with Examples

Itertools Module:

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings.

Itertools.compress() Function:

Itertools.compress() belongs to the class of terminating iterators. This means that these iterators are used to process short input sequences and generate output based on the functionality of the method.

This iterator selects the values to print from the passed container based on the boolean list value passed as an additional argument. If boolean true, the arguments are printed; otherwise, all are skipped.

We give the function two parameters in this case. The first parameter is an iterator, and the second is a selector that can be True/1 or False/0. If the first parameter’s corresponding selector is True, the corresponding data will be printed, and the output will reflect this.

 

Syntax:

compress(iterator, selector)

Examples:

Example1:

Input:

Given List = ['hello', 'this', 'is', 'btechgeeks']
Given selectors List = [True, False, False, True]

Output:

hello
btechgeeks

Explanation:

Here, In the selection list, first element is True. so, it prints the
respective index element from the given list 'hello'.
If it is False, respective index element from the given list gets skipped.
Therefore it prints only 'hello' and 'btechgeeks' from given list.

Example2:

Input:

Given String = "hello"
Given selectors List = [0, 1, 0, 1, 1]

Output:

e
l
o

Itertools.compress() Function with Examples in Python

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

Approach:

  • Import itertools module using the import keyword.
  • Import operator module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Give the selectors list as static input and store it in another variable.
  • Pass the given list and selectors list as the arguments to the itertools.compress() function where If boolean True in selectors list, the respective arguments in the given list are printed; otherwise, all are skipped.
  • Store it in another variable.
  • Iterate in the above result iterable using the for loop.
  • Inside the loop, print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# Import operator module using the import keyword.
import operator

# Give the list as static input and store it in a variable.
gvn_lst = ['hello', 'this', 'is', 'btechgeeks']
# Give the selectors list as static input and store it in another variable.
gvn_selectrs = [True, False, False, True]
# Pass the given list and selectors list as the arguments to the itertools.compress()
# function where If boolean True in selectors list, the respective arguments in the
# given list are printed; otherwise, all are skipped.
# Store it in another variable.
rslt = itertools.compress(gvn_lst, gvn_selectrs)
# Iterate in the above result iterable using the for loop.
for itr in rslt:
    # Inside the loop, print the iterator value.
    print(itr)

Output:

hello
btechgeeks
Using 1, 0 Boolean values:
# Import itertools module using the import keyword.
import itertools
# Import operator module using the import keyword.
import operator

# Give the string as static input and store it in a variable.
gvn_str = "hello"
# Give the selectors list as static input and store it in another variable.
gvn_selectrs = [0, 1, 0, 1, 1]
# Pass the given str and selectors list as the arguments to the itertools.compress()
# function where If boolean True(1) in selectors list, the respective arguments in the
# given string are printed; otherwise, all are skipped.
# Store it in another variable.
rslt = itertools.compress(gvn_str, gvn_selectrs)
# Iterate in the above result iterable using the for loop.
for itr in rslt:
    # Inside the loop, print the iterator value.
    print(itr)

Output:

e
l
o

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

Approach:

  • Import itertools module using the import keyword.
  • Import operator module using the import keyword.
  • Give the list as user input using list(), input(),and split() functions.
  • Store it in a variable.
  • Give the selectors list as user input using list(), input(),and split() functions.
  • Store it in another variable.
  • Converting to boolean data type
  • Loop in the given selectors list using the for loop
  • If the iterator value of the given selectors list is ‘True’, then modify the list item with the boolean True.
  • Else modify the list item with the boolean False.
  • Pass the given list and selectors list as the arguments to the itertools.compress() function where If boolean True in selectors list, the respective arguments in the given list are printed; otherwise, all are skipped.
  • Store it in another variable.
  • Iterate in the above result iterable using the for loop.
  • Inside the loop, print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools
# 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 selectors list as user input using list(),input(),and split() functions.
# Store it in a variable.
gvn_selectrs = list(input(
   'Enter some random List Elements separated by spaces = ').split())
#converting to boolean data type
# Loop in the given selectors list using the for loop
for i in range(len(gvn_selectrs)):
    # If the iterator value of the given selectors list is 'True',then 
    # modify the list item with the boolean True.
    if(gvn_selectrs[i]=='True'):
        gvn_selectrs[i]=True
    # Else modify the list item with the boolean False.
    else:
        gvn_selectrs[i]=False
       

# Pass the given list and selectors list as the arguments to the itertools.compress()
# function where If boolean True in selectors list, the respective arguments in the
# given list are printed; otherwise, all are skipped.
# Store it in another variable.
rslt = itertools.compress(gvn_lst, gvn_selectrs)
# Iterate in the above result iterable using the for loop.
for itr in rslt:
    # Inside the loop, print the iterator value.
    print(itr)

Output:

Enter some random List Elements separated by spaces = 10 20 30
Enter some random List Elements separated by spaces = True False True
10
30

Python Itertools.compress() Function with Examples Read More »

Python Itertools.dropwhile() Function with Examples

Itertools Module:

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings.

Itertools.dropwhile() Function:

Only after the func. in argument returns false for the first time does Python’s dropwhile() function return an iterator.

Syntax:

dropwhile(function, sequence)

Examples:

Example1:

Input:

Given List = [6, 7, -3, -1, 4]

Output:

[-3, -1, 4]

Explanation:

Here it removes the positive numbers 6, 7 and the condition becomes false 
when the number the number is -3. so, the list remains unchanged afterwards.

Example2:

Input:

Given List = [3, 6, 8, -4, -9, 10, 56]

Output:

[-4, -9, 10, 56]

Itertools.dropwhile() Function with Examples in Python

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

Approach:

  • Import itertools module using the import keyword.
  • Create a function say checkpositive which accepts the number as argument and returns True if the number is greater than 0.
  • Inside the function, return True if the given argument is greater than 0.
  • Give the list as static input and store it in a variable.
  • Pass the above function and given list as the arguments to the itertools.dropwhile()  function and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools

# Create a function say checkpositive which accepts the number as argument and
# returns True if the number is greater than 0.


def checkpositive(num):
    # Return True if the given argument is greater than 0
    return num > 0


# Give the list as static input and store it in a variable.
gvn_lst = [6, 7, -3, -1, 4]
# Pass the above function and given list as the arguments to the
# itertools.dropwhile()  function and store it in a variable.
rslt = itertools.dropwhile(checkpositive, gvn_lst)
# Convert the above result into a list using the list() function and store it
# in another variable.
rslt_lst = list(rslt)
# Print the above result.
print(rslt_lst)

Output:

[-3, -1, 4]

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

Approach:

  • Import itertools module using the import keyword.
  • Create a function say checkpositive which accepts the number as argument and returns True if the number is greater than 0.
  • Inside the function, return True if the given argument is greater than 0.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Pass the above function and given list as the arguments to the itertools.dropwhile()  function and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools

# Create a function say checkpositive which accepts the number as argument and
# returns True if the number is greater than 0.


def checkpositive(num):
    # Return True if the given argument is greater than 0
    return num > 0


# 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 above function and given list as the arguments to the
# itertools.dropwhile()  function and store it in a variable.
rslt = itertools.dropwhile(checkpositive, gvn_lst)
# Convert the above result into a list using the list() function and store it
# in another variable.
rslt_lst = list(rslt)
# Print the above result.
print(rslt_lst)

Output:

Enter some random List Elements separated by spaces = 3 6 8 -4 -9 10 56
[-4, -9, 10, 56]

Python Itertools.dropwhile() Function with Examples Read More »

Python Itertools.filterfalse() Function with Examples

Itertools Module:

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings.

Itertools.filterfalse() Function:

This iterator prints only values for the passed function that return false.

Syntax:

filterfalse(function or None, sequence)

Parameter Values:

filterfalse() method takes two arguments: function or None as the first and a list of integers as the second argument.

Return Value:

This method returns the only values for the passed function that return false.

Itertools.filterfalse() Function with Examples in Python

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

 With giving Function as None

Approach:

  • Import itertools module using the import keyword.
  • Import filterfalse() function from itertools using the import keyword.
  • Loop using the filterfalse() function and for loop by passing the arguments as function(None) and range.
  • Give the list as static input and store it in a variable.
  • Use the filterfalse() function by passing the arguments as given function(None) and list for slicing the given list.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword
import itertools
# Import filterfalse() function from itertools using the import keyword.
from itertools import filterfalse


# Loop using the filterfalse() function and for loop by passing the arguments
# as function(None) and range.
for itr in filterfalse(None, range(15)):
    print(itr)

# Give the list as static input and store it in a variable.
gvn_lst = [1, 4, 6, 3, 8]
# Use the filterfalse() function by passing the arguments as given function(None)
# and list for slicing the given list.
# Store it in another variable.
rslt = itertools.filterfalse(None, gvn_lst)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print(rslt_lst)

Output:

0
[]
With giving Function :

Approach:

  • Import itertools module using the import keyword.
  • Import filterfalse() function from itertools using the import keyword.
  • Create a function say Demo_function which accepts the number as argument and returns True if the number is greater than 7.
  • Inside the function, return True if the given argument is greater than 7.
  • Give the list as static input and store it in a variable.
  • Use the filterfalse() function by passing the arguments as above function and given list for slicing the given list.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword
import itertools
# Import filterfalse() function from itertools using the import keyword.
from itertools import filterfalse

# Create a function say Demo_function which accepts the number as argument and
# returns True if the number is greater than 7.


def Demo_function(num):
    # Return True if the given argument is greater than 7
    return (num > 7)


# Give the list as static input and store it in a variable.
gvn_lst = [1, 3, 4, 8, 11]
# Use the filterfalse() function by passing the arguments as above function
# and given list for slicing the given list.
# Store it in another variable.
rslt = itertools.filterfalse(Demo_function, gvn_lst)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print(rslt_lst)

Output:

[1, 3, 4]

Using lambda() Function

# Import itertools module using the import keyword
import itertools
# Import filterfalse() function from itertools using the import keyword.
from itertools import filterfalse
# Give the list as static input and store it in a variable.
gvn_lst = [1, 2, 3, 4, 7, 8, 6, 9]

#  Use the filterfalse() function for slicing the given list
print(list(itertools.filterfalse(lambda num: num % 2 != 0, gvn_lst)))

Output:

[2, 4, 8, 6]

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

Approach:

  • Import itertools module using the import keyword.
  • Import filterfalse() function from itertools using the import keyword.
  • Create a function say Demo_function which accepts the number as argument and returns True if the number is greater than 7.
  • Inside the function, return True if the given argument is greater than 7.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Use the filterfalse() function by passing the arguments as above function and given list for slicing the given list.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword
import itertools
# Import filterfalse() function from itertools using the import keyword.
from itertools import filterfalse

# Create a function say Demo_function which accepts the number as argument and
# returns True if the number is greater than 7.


def Demo_function(num):
    # Return True if the given argument is greater than 7
    return (num > 7)


# 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()))
# Use the filterfalse() function by passing the arguments as above function
# and given list for slicing the given list.
# Store it in another variable.
rslt = itertools.filterfalse(Demo_function, gvn_lst)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print(rslt_lst)

Output:

Enter some random List Elements separated by spaces = -2 -3 2 4 6 10 13
[-2, -3, 2, 4, 6]

Python Itertools.filterfalse() Function with Examples Read More »

Python Itertools.islice() Function with Examples

Itertools Module:

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings.

Itertools.islice() Function:

This iterator prints only the values specified in the iterable container passed as an argument.

Syntax:

islice(iterable, start, stop, step)

Examples:

Example1:

Input:

Given list = [10, 20, 30, 40]
Given start = 2
Given stop =  25
Given step = 3

Output:

[30]

Example2:

Input:

Given list = [2, 5, 6, 7, 8]
Given start = 3
Given stop = 20
Given step = 3

Output:

[7]

Itertools.islice() Function with Examples in Python

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

Approach:

  • Import islice() function from itertools using the import keyword.
  • Loop using the islice and for loop by passing the arguments range and stepvalue.
  • Inside the loop, print the iterator value.
  • Give the list as static input and store it in a variable.
  • Use the islice() function by passing the arguments given list, start, end, and step values for slicing the given list.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import islice() function from itertools using the import keyword.
from itertools import islice


# Loop using the islice function and for loop by passing the arguments as range
# and stepvalue.
for itr in islice(range(15), 2):
    # Inside the loop, print the iterator value.
    print(itr)

# Give the list as static input and store it in a variable.
gvn_lst = [1, 4, 2, 3, 8, 9]
# Use the islice() function by passing the arguments given list, start, end, and
# step values for slicing the given list.
# Store it in another variable.
rslt = islice(gvn_lst, 2, 5, 2)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print(rslt_lst)

Output:

0
1
[2, 8]

Similarly, try for the other examples

Here we are giving range, start and stop values as arguments to the islice() function

# Import islice() function from itertools using the import keyword.
from itertools import islice

# Loop using the islice function and for loop by passing the arguments as range
# start, stop values.
for itr in islice(range(23), 2, 10):
    print(itr)

Output:

2
3
4
5
6
7
8
9

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

Approach:

  • Import islice() function from itertools using the import keyword.
  • Loop using the islice and for loop by passing the arguments range and stepvalue.
  • Inside the loop, print the iterator value.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the start value as user input using the int(input()) function and store it in a variable.
  • Give the stop value as user input using the int(input()) function and store it in another variable.
  • Give the step value as user input using the int(input()) function and store it in another variable.
  • Use the islice() function by passing the arguments given list, start, end, and step values for slicing the given list.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import islice() function from itertools using the import keyword.
from itertools import islice


# 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 start value as user input using the int(input()) function and store it in a variable.
gvn_strt = int(input("Enter some random number = "))
# Give the stop value as user input using the int(input()) function and store it in another variable.
gvn_stop = int(input("Enter some random number = "))
# Give the step value as user input using the int(input()) function and store it in another variable.
gvn_step = int(input("Enter some random number = "))
# Use the islice() function by passing the arguments given list, start, end, and
# step values for slicing the given list.
# Store it in another variable.
rslt = islice(gvn_lst, gvn_strt, gvn_stop, gvn_step)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print(rslt_lst)

Output:

Enter some random List Elements separated by spaces = 10 20 30 40
Enter some random number = 2
Enter some random number = 25
Enter some random number = 3
[30]

 

 

Python Itertools.islice() Function with Examples Read More »