• Latest
  • Trending
All You Need to Know About the Python Itertools Module

All You Need to Know About the Python Itertools Module

March 9, 2022
Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
Instagram fined €405m over children’s data privacy

Instagram fined €405m over children’s data privacy

September 6, 2022
8 Most Common Causes of a Data Breach

5.7bn data entries found exposed on Chinese VPN

August 18, 2022
Fibre optic interconnection linking Cameroon and Congo now operational

Fibre optic interconnection linking Cameroon and Congo now operational

July 15, 2022
Ericsson and MTN Rwandacell Discuss their Long-Term Partnership

Ericsson and MTN Rwandacell Discuss their Long-Term Partnership

July 15, 2022
Airtel Africa Purchases $42M Worth of Additional Spectrum

Airtel Africa Purchases $42M Worth of Additional Spectrum

July 15, 2022
Huawei steps up drive for Kenyan talent

Huawei steps up drive for Kenyan talent

July 15, 2022
TSMC predicts Q3 revenue boost thanks to increased iPhone 13 demand

TSMC predicts Q3 revenue boost thanks to increased iPhone 13 demand

July 15, 2022
Facebook to allow up to five profiles tied to one account

Facebook to allow up to five profiles tied to one account

July 15, 2022
Top 10 apps built and managed in Ghana

Top 10 apps built and managed in Ghana

July 15, 2022
MTN Group to Host the 2nd Edition of the MoMo API Hackathon

MTN Group to Host the 2nd Edition of the MoMo API Hackathon

July 15, 2022
KIOXIA Introduce JEDEC XFM Removable Storage with PCIe/NVMe Spec

KIOXIA Introduce JEDEC XFM Removable Storage with PCIe/NVMe Spec

July 15, 2022
  • Consumer Watch
  • Kids Page
  • Directory
  • Events
  • Reviews
Sunday, 5 February, 2023
  • Login
itechnewsonline.com
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion
Subscription
Advertise
No Result
View All Result
itechnewsonline.com
No Result
View All Result

All You Need to Know About the Python Itertools Module

Itertools is a common Python module, but how much do you know about it? Find out more by exploring some of the module's most useful functions.

by ITECHNEWS
March 9, 2022
in Data Science, Leading Stories
0 0
0
All You Need to Know About the Python Itertools Module

Itertools is one of the most useful modules Python provides. Its functions make it a breeze to work with lists and arrays. Whether you need all permutations of the values in an array, or you want to group characters from a string, Itertools can help.

Writing the code for such common cases can be tedious and error-prone. Hence, developers have built libraries to do all this for you. You can use these functions by importing Itertools. In this article, you’ll learn about the Itertools module in Python and its functions.

YOU MAY ALSO LIKE

Inaugural AfCFTA Conference on Women and Youth in Trade

Instagram fined €405m over children’s data privacy

What Is the Itertools Module?

The official Python documentation explains that Itertools contains code for building iterators. This module provides fast and efficient functions to work with lists and arrays.

Before using this module, you need to import it using the following syntax:

import itertools

There are three different types of iterators present in this module.

  1. Infinite iterators
  2. Combinatoric iterators
  3. Terminating iterators

Infinite Iterators

Infinite iterators can run a loop infinitely. These functions more often run using a for loop. There are three infinite iterators.

1. count(start, step)

The count() function takes two parameters: the start and the step. The loop begins from the start value and returns values that increment by step, which defaults to 1. Consider the example given below: the loop starts from 2 and will add 2 each time. The loop breaks when the value of i becomes 10.

for i in itertools.count(2,2):
  if i == 10:
      break
  else:
      print(i, end=" ")

Output:

2  4  6  8  

2. repeat(number, timesToRepeat)

The repeat() function accepts two parameters. The first is a value that the function produces repeatedly. The second parameter is the number of times the number should repeat. If you don’t specify the second parameter, the loop will run infinitely.

for i in itertools.repeat(2,5):
   print(i, end=" ")

Output:

2 2 2 2 2 

3. cycle(input)

The cycle() function iterates through the input and prints individual items in a given order. When it reaches the end of its input, cycle restarts from the beginning.

c = 0
var = "12345"
for i in itertools.cycle(var):
  if c == 12:
      break
  else:
      c = c + 1
      print(i, end=" ")

Output:

1 2 3 4 5 1 2 3 4 5 1 2

Combinatoric iterators

The combinatoric iterators provide functions to perform permutations, combinations, and cartesian products.

1. product(input)

The product() function computes the cartesian product of the specified input. It has a repeat parameter that computes the cartesian product of an iterator with itself. It is an optional parameter.

array = [1,2,3]
print(list(itertools.product(array, repeat=2)))
string = "ABC"
print(list(itertools.product(string, "XYZ")))

Output:

Example 1 [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
Example 2 [('A', 'X'), ('A', 'Y'), ('A', 'Z'), ('B', 'X'), ('B', 'Y'), ('B', 'Z'), ('C', 'X'), ('C', 'Y'), ('C', 'Z')]

2. permutations(input, size)

This function returns a tuple of all the permutations of the given iterable. It accepts two parameters: the iterable and group size. If the group size is not specified, it will form groups of the same length as the iterable itself.

arr = [1,2,3,4]
print(list(itertools.permutations(arr, 2)))

Output:

[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]

 

3. combinations(input, length)

The combinations() function helps to compute the combinations of the given iterator. Note that this function maintains the item order of its input. While permutations includes values that differ only by order, combinations produces unique values.

arr = [1,2,3,4]
print(list(itertools.combinations(arr, 3)))

Output:

[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

Terminating iterators

Terminating iterators produce output based on the conditions given to the input. You can understand it best from some example functions.

1. accumulate(input, operator)

The accumulate() function accepts two arguments: the iterable and an operator. It produces output by applying the operator to a cumulative total and each input element in turn. The operator is an optional argument. If you don’t pass it, this function will perform addition.

import operator
arr = [1,2,3,4]
print(list(itertools.accumulate(arr)))
print(list(itertools.accumulate(arr, operator.sub)))

Output:

[1, 3, 6, 10]
[1, -1, -4, -8]

2. starmap(function, input)

The starmap() function accepts a function and tuple list as its arguments. It computes return values by applying the function to each tuple in the input. In the example given, this function will compute the maximum value of each tuple and return it in an array.

arr = [(1,2,3), (4,5,6), (7,8,9)]
print(list(itertools.starmap(max, arr)))

Output:

[3, 6, 9]

3. filterfalse(function)

The filterfalse() function returns values that don’t meet the condition in the passed function. The code given below removes all the odd values.

arr = [1,2,3,4]
print(list(itertools.filterfalse(lambda x : x % 2 != 0, arr))) 

Output:

[2, 4]

Continue Your Python Coding Journey

Now that you have learned about the Itertools module, it’s time to explore other Python modules. Python has modules and libraries for a wide set of tasks. They include advanced concepts like Fourier transformation and AI/ML applications.

Source: UNNATI BAMANIA
Via: makeuseof
Tags: Python Itertools Module
ShareTweetShare
Plugin Install : Subscribe Push Notification need OneSignal plugin to be installed.

Search

No Result
View All Result

Recent News

Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
Instagram fined €405m over children’s data privacy

Instagram fined €405m over children’s data privacy

September 6, 2022
8 Most Common Causes of a Data Breach

5.7bn data entries found exposed on Chinese VPN

August 18, 2022

About What We Do

itechnewsonline.com

We bring you the best Premium Tech News.

Recent News With Image

Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
Instagram fined €405m over children’s data privacy

Instagram fined €405m over children’s data privacy

September 6, 2022

Recent News

  • Inaugural AfCFTA Conference on Women and Youth in Trade September 6, 2022
  • Instagram fined €405m over children’s data privacy September 6, 2022
  • 5.7bn data entries found exposed on Chinese VPN August 18, 2022
  • Fibre optic interconnection linking Cameroon and Congo now operational July 15, 2022
  • Home
  • InfoSec
  • Opinion
  • Africa Tech
  • Data Storage

© 2021-2022 iTechNewsOnline.Com - Powered by BackUPDataSystems

No Result
View All Result
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion

© 2021-2022 iTechNewsOnline.Com - Powered by BackUPDataSystems

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
Go to mobile version