Python

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.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 »

Python Itertools.starmap() 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.starmap() Function:

When an iterable is contained within another iterable and a function must be applied to both of them, starmap() is used. Each element of an iterable within another iterable is treated as a separate item by starmap(). It is comparable to a map (). This function belongs to the category of terminating iterators.

A built-in function, a user-defined function, or even a lambda function can be used.

Syntax:

starmap(function, iterable)

Parameters

function: This is Required. Procedures to be executed on iterable data.

iterable: This is Required. Elements that will be passed to the function.

Examples:

Example1:

Input:

Given List = [(6, 2), (5, 5), (2, 9), (7, 1), (0, 3)]
function: lambda a, b: a + b

Output:

[8, 10, 11, 8, 3]

Example2:

Input:

Given List = [(6, 2), (5, 5), (2, 9), (7, 1), (0, 3)]
function: lambda a, b: a * b

Output:

[12, 25, 18, 7, 0]

Itertools.starmap() Function with Examples in Python

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

1)Using Lambda Function

Approach:

  • Import starmap() function from itertools using the import keyword.
  • Give the list as static input and store it in a variable.
  • Pass lambda() function and given list as the arguments to the starmap() function where lambda() function adds the two numbers and 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 starmap() function from itertools using the import keyword.
from itertools import starmap
# Give the list as static input and store it in a variable.
gvn_lst = [(6, 2), (5, 5), (2, 9), (7, 1), (0, 3)]
# Pass lambda() function and given list as the arguments to the starmap() function
# where lambda() function adds the two numbers and store it in another variable.
rslt = starmap(lambda a, b: a + b, 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:

[8, 10, 11, 8, 3]
2)Function Using def

Approach:

  • Import starmap() function from itertools using the import keyword.
  • Create a function say Multiplication which accepts three numbers as arguments and returns the multiplication of three numbers.
  • Inside the function, Return multiplication of given three arguments.
  • Give the list as static input and store it in a variable.
  • Pass the above function(Multiplication) and given list as the arguments to the starmap() function where Multiplication() function multiplies the three numbers and 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 starmap() function from itertools using the import keyword.
from itertools import starmap
# Create a function say Multiplication which accepts three numbers as arguments and
# returns the multiplication of three numbers


def Multiplication(p, q, r):
    # Return multiplication of given three arguments
    return p*q*r


# Give the list as static input and store it in a variable.
gvn_lst = [(2, 5, 4), (1, 10, 2), (3, 5, 2)]
# Pass the above function(Multiplication) and given list as the arguments to the
# starmap() function where Multiplication() function multiplies the three numbers
# and store it in another variable.
rslt = starmap(Multiplication, 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:

[40, 20, 30]

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

Python Itertools.takewhile() 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.takewhile() Function:

This allows you to consider an iterable item until the specified predicate becomes false for the first time. In most cases, the iterable is a list or a string.

It “takes” the element from the sequence “while” the predicate is “true,” as the name implies. This function belongs to the category of “terminating iterators.” The output cannot be used directly and must be converted to another iterable form before it can be used. They are mostly converted into lists.

The predicate can be either a built-in or a user-defined function. Lambda functions can also be used.

General Implementation Format:

def takewhile_function(gvn_predicte, gvn_itrable):
for itr in gvn_itrable:
    if gvn_predicte(itr):
        return(itr)
    else:
        break

Syntax:

takewhile(predicate, iterable)

Parameters

predicate: This is Required. Iterable items are evaluated by the function.

iterable: This is Required. Elements that will be checked over a predicate.

Examples:

Example1:

Input:

Given List =  [3, 7, 6, 4, 5, 8]
function: num % 2 != 0

Output:

[3, 7]

Example2:

Input:

Given string =  "hello123all"
function: character.isalpha()

Output:

h
e
l
l
o

Itertools.takewhile() Function with Examples in Python

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

1)For Lists

Approach:

  • Import takewhile() function from itertools using the import keyword.
  • Create a function say check_oddnumbers which accepts the number as an argument and returns True if it is an odd number.
  • Inside the function, Return if the number is odd.
  • Give the list as static input and store it in a variable.
  • Pass the above function(check_oddnumbers) and given list as the arguments to the takewhile() function where check_oddnumbers()  function returns the odd numbers.
  • 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 takewhile() function from itertools using the import keyword.
from itertools import takewhile

# Create a function say check_oddnumbers which accepts the number as an argument and
# returns True if it is an odd number


def check_oddnumbers(num):
    # Return if the number is odd.
    return(num % 2 != 0)


# Give the list as static input and store it in a variable.
gvn_lst = [3, 7, 6, 4, 5, 8]
# Pass the above function(check_oddnumbers) and given list as the arguments to the
# takewhile() function where check_oddnumbers() function returns the odd numbers
# and store it in another variable.
rslt = takewhile(check_oddnumbers, 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, 7]
2)For Strings

Approach:

  • Import takewhile() function from itertools using the import keyword.
  • Create a function say check_isalpha which accepts the character as an argument and returns True if the character is an alphabet.
  • Inside the function, Return if the argument(character) is an alphabet.
  • Give the string as static input and store it in a variable.
  • Loop using the takewhile() function and for loop by passing the arguments as the above check_isalpha function and given string.
  • Inside the loop, print the iterator value.
  • The Exit of the Program.

Below is the implementation:

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

# Create a function say check_isalpha which accepts the character as an argument
# and returns True if the character is an alphabet.


def check_isalpha(ch):
    # Return if the argument(character) is an alphabet.
    return(ch.isalpha())


# Give the string as static input and store it in a variable.
gvn_str = "hello1234all"
# Loop using the takewhile() function and for loop by passing the arguments as
# the above check_isalpha function and given string.

for itr in takewhile(check_isalpha, gvn_str):
    # Inside the loop, print the iterator value.
    print(itr)

Output:

h
e
l
l
o

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

Approach:

  • Import takewhile() function from itertools using the import keyword.
  • Create a function say check_oddnumbers which accepts the number as an argument and returns True if it is an odd number.
  • Inside the function, Return if the number is odd.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Pass the above function(check_oddnumbers) and given list as the arguments to the takewhile() function where check_oddnumbers()  function returns the odd numbers.
  • 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 takewhile() function from itertools using the import keyword.
from itertools import takewhile

# Create a function say check_oddnumbers which accepts the number as an argument and
# returns True if it is an odd number


def check_oddnumbers(num):
    # Return if the number is odd.
    return(num % 2 != 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(check_oddnumbers) and given list as the arguments to the
# takewhile() function where check_oddnumbers function returns the odd numbers.
# Store it in another variable.
rslt = takewhile(check_oddnumbers, 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 = 9 7 5 2 8 3
[9, 7, 5]
2)For Strings

Approach:

  • Import takewhile() function from itertools using the import keyword.
  • Create a function say check_isalpha which accepts the character as an argument and returns True if the character is an alphabet.
  • Inside the function, Return if the argument(character) is an alphabet.
  • Give the string as user input using the input() function and store it in a variable.
  • Loop using the takewhile() function and for loop by passing the arguments as the above check_isalpha function and given string.
  • Inside the loop, print the iterator value.
  • The Exit of the Program.

Below is the implementation:

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

# Create a function say check_isalpha which accepts the character as an argument
# and returns True if the character is an alphabet.


def check_isalpha(ch):
    # Return if the character is an alphabet.
    return(ch.isalpha())


# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Loop using the takewhile function and for loop by passing the arguments as
# the above check_isalpha function and given string.

for itr in takewhile(check_isalpha, gvn_str):
    # Inside the loop, print the iterator value.
    print(itr)

Output:

Enter some random string = abc567yiu
a
b
c

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

Python Itertools.tee() 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.tee() Function:

This iterator divides the container into the iterators specified in the argument.

Syntax:

tee(iterator, count)

Parameters

iterator: It is an iterator.

count: It is an integer.

Return Value:

The number of iterators specified in the argument is returned by this method.

Examples:

Example1:

Input:

Given list =  [1, 3, 5, 2, 7]
Given count = 4

Output:

The following iterators : 
[1, 3, 5, 2, 7]
[1, 3, 5, 2, 7]
[1, 3, 5, 2, 7]
[1, 3, 5, 2, 7]

Example2:

Input:

Given list = [2, 4,  8,  1,  3]
Given count = 2

Output:

The following iterators : 
[2, 4, 8, 1, 3]
[2, 4, 8, 1, 3]

Itertools.tee() 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.
  • Get the iterator of the given list using the iter() function.
  • Store it in a variable.
  • Pass the above iterator and some random count value as the arguments to the itertools.tee() function and store it in another variable.
  • Loop till the given count value using the for loop.
  • Inside the loop, print the list of iterator values of the above result.
  • 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 = [1, 3, 5, 2, 7]

# Get the iterator of the given list using the iter() function.
# Store it in a variable.
itertr = iter(gvn_lst)

# Pass the above iterator and some random count value as the arguments to the
# itertools.tee() function and store it in another variable.

# Using tee() function to create a list of iterators results in a given list of
# 4 iterators with the same values.
rslt = itertools.tee(itertr, 4)

# Loop till the given count value using the for loop.
print("The following iterators : ")
for itr in range(0, 4):
    # Print the list of iterator values of the above rslt.
    print(list(rslt[itr]))

Output:

The following iterators : 
[1, 3, 5, 2, 7]
[1, 3, 5, 2, 7]
[1, 3, 5, 2, 7]
[1, 3, 5, 2, 7]

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.
  • Give the count value as user input using the int(input()) function and store it in another variable.
  • Get the iterator of the given list using the iter() function.
  • Store it in a variable.
  • Pass the above iterator and the given count value as the arguments to the itertools.tee() function and store it in another variable.
  • Loop till the given count value using the for loop.
  • Inside the loop, print the list of iterator values of the above result.
  • 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 count value as user input using the int(input()) function 
# and store it in a variable.
gvn_cnt = int(input("Enter some random number = "))
# Get the iterator of the given list using the iter() function.
# Store it in a variable.
itertr = iter(gvn_lst)

# Pass the above iterator and the given count value as the arguments to the
# itertools.tee() function and store it in another variable.

# Using tee() function to create a list of iterators results in a given list of
# given count number of iterators with the same values.
rslt = itertools.tee(itertr, gvn_cnt)

# Loop till the given count value using the for loop.
print("The following iterators : ")
for itr in range(0, gvn_cnt):
    # Print the list of iterator values of the above rslt.
    print(list(rslt[itr]))

Output:

Enter some random List Elements separated by spaces = 2 4 8 1 3
Enter some random number = 2
The following iterators : 
[2, 4, 8, 1, 3]
[2, 4, 8, 1, 3]

 

 

 

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