Photo by Christin Hume on Unsplash
If you have been doing python, you must have definitely come across the itertools module. It might not look like it, but I can tell you that it is one of the most powerful libraries on python. If you wish to write a more efficient, clean, and more ‘pythonic’ code, I believe that itertools is a must-have tool to add to your arsenal. Here in this article we will introduce some functionalities of the library and delve into some examples to help us better understand it.
However, the thing about itertools is that it is not enough to just know the definitions of the functions it contains. The real power lies in composing these functions to create fast, memory-efficient, and good-looking code. So here we will look at definitions along with some practical examples of the functions to understand their applications.
For an overview let us look at what the module’s official documentation has to say:
The module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an “iterator algebra” making it possible to construct specialized tools succinctly and efficiently in pure Python
Itertools provides us with three different types of iterators
Let’s now dive into it
Python iterators like lists, tuples, dictionaries are exhaustive. But it is not necessary for an iterator to exhaust at some point, they can go on forever. Let’s look at the three types of infinite iterators.
from itertools import count | |
for i in count(0,2): | |
print(i, end = " ") | |
if i==20: | |
break | |
# OUTPUT | |
''' | |
0 2 4 6 8 10 12 14 16 18 20 | |
''' |
We can also pass negative and floating arguments to this function.
from itertools import count | |
count_floating_negative = count(start=0.5, step = -0.5) | |
print(list(next(count_floating_negative) for _ in range(10))) | |
# OUTPUT | |
''' | |
[0.5, 0.0, -0.5, -1.0, -1.5, -2.0, -2.5, -3.0, -3.5, -4.0] | |
''' |
from itertools import cycle | |
count = 0 | |
for i in cycle('ABC'): | |
print(i, end = ' ') | |
count += 1 | |
if count == 6: | |
break | |
# OUTPUT | |
''' | |
A B C A B C | |
''' |
Now use the next function to print the values.
from itertools import repeat | |
for i in repeat(1,5): | |
print(i, end = ' ') | |
#OUTPUT | |
''' | |
1 1 1 1 1 | |
''' |
A common use of this iterator is to supply a stream of values to map() or zip().
from itertools import repeat | |
print(list(map(pow, range(10), repeat(2)))) | |
#Prints the square of all numbers in range(10) | |
#OUTPUT | |
''' | |
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] |
That was all about infinite iterators. From the above examples, it is clear that there may e situations where these can come in handy. Now let’s look at the real deal of the itertools library. The terminating iterators.
These iterators are used to work on finite sequences and produce an output based on the function used.
func
argument). If func
is supplied, it should be a function of two arguments. Elements of the input iterable may be any type that can be accepted as arguments to func
. It will become more clear with some examples.
from itertools import accumulate | |
from operator import mul | |
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
print(list(accumulate(iterable))) | |
# Prints the addition after each iteration | |
# OUTPUT | |
""" | |
[1, 3, 6, 10, 15, 21, 28, 36, 45, 55] | |
""" | |
print(list(accumulate(iterable, mul))) | |
# Prints the mutiplication after each iteration (= factorial of the number) | |
""" | |
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800] | |
""" |
Let’s pass the optional func
argument to accumulate.
from itertools import accumulate | |
data = [-1, 2, 5, 7, -20, 9, 12, 9, 16, 4] | |
print(list(accumulate(data, min))) | |
#Prints the running minimum of the data | |
#OUTPUT | |
''' | |
[-1, -1, -1, -1, -20, -20, -20, -20, -20, -20] | |
''' | |
print(list(accumulate(data, max))) | |
#Prints the running maximum of the data | |
#OUTPUT | |
''' | |
[-1, 2, 5, 7, 7, 9, 12, 12, 16, 16] | |
''' | |
my_func = lambda a,b: (a + b) * 2 | |
print(list(accumulate(data, my_func))) | |
#Prints the output calculated by the my_func | |
#OUTPUT | |
''' | |
[-1, 2, 14, 42, 44, 106, 236, 490, 1012, 2032] | |
''' |
It is very similar functools.reduce()
which returns only the last accumulated value, but that is a story for another day!
chain.from_iterabe()
which works in a similar fashion, but it takes an argument as a list of lists instead of multiple lists.
from itertools import chain | |
for i in chain([0,1,2,3], range(4,11), 'ABC'): | |
print(i, end = ' ') | |
#OUTPUT | |
''' | |
0 1 2 3 4 5 6 7 8 9 10 A B C | |
''' | |
my_iterable = [[0,1,2],[3,4],[5,6,7,8,9,10],['ABC']] | |
for i in chain.from_iterable(my_iterable): | |
print(i, end = ' ') | |
#OUTPUT | |
''' | |
0 1 2 3 4 5 6 7 8 9 10 ABC | |
''' |
from itertools import compress | |
data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] | |
selector = [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] | |
for i in compress(data, selector): | |
print(i, end=" ") | |
# OUTPUT | |
# Simply prints all numbers for which the corresponding boolean value in selector | |
#is True, in this case all the even numbers upto 10. | |
""" | |
0 2 4 6 8 10 | |
""" |
predicate
in argument returns false for the first time.
from itertools import dropwhile | |
iterable = [1, 3, 5, 7, 2, 4, 6, 9, 11] | |
predicate = lambda x: x%2==1 | |
for i in dropwhile(predicate, iterable): | |
print(i, end = ' ') | |
# OUTPUT | |
""" | |
2 4 6 9 11 | |
""" |
False
. If predicate is None
, it returns the items that are false.
from itertools import filterfalse | |
iterable = [1, 3, 5, 7, 2, 4, 6, 9, 11] | |
predicate = lambda x: x%2==0 | |
for i in filterfalse(predicate, iterable): | |
print(i, end = ' ') | |
# OUTPUT | |
""" | |
1 3 5 7 9 11 | |
""" |
None
, key defaults to an identity function and returns the element unchanged.
from itertools import groupby | |
a_list = [("Even", 2), | |
("Odd", 5), | |
("Even", 8), | |
("Odd", 3)] | |
iterator = groupby(a_list, key = lambda x:x[0]) | |
for key, group in iterator: | |
key_and_group = {key : list(group)} | |
print(key_and_group) | |
# OUTPUT | |
""" | |
{'Even': [('Even', 2)]} | |
{'Odd': [('Odd', 5)]} | |
{'Even': [('Even', 8)]} | |
{'Odd': [('Odd', 3)]} | |
""" |
from itertools import islice | |
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
for i in islice(l, 1, 9, 1): | |
print(i, end =' ') | |
# OUTPUT | |
""" | |
2 3 4 5 6 7 8 9 | |
""" |
from itertools import starmap | |
from operator import add, mul | |
iterable = [(1,3), (2,4), (3,0), (5,6)] | |
for i in starmap(add, iterable): | |
print(i, end = ' ') | |
# 4 6 3 11 | |
for i in starmap(mul, iterable): | |
print(i, end = ' ') | |
# 3 8 0 30 | |
for i in starmap(min, iterable): | |
print(i, end = ' ') | |
# 1 2 0 5 |
dropwhile
.
from itertools import takewhile | |
iterable = [1, 3, 5, 7, 2, 4, 6, 9, 11] | |
predicate = lambda x: x%2==1 | |
for i in takewhile(predicate, iterable): | |
print(i, end = ' ') | |
# OUTPUT | |
""" | |
1 3 5 7 | |
""" |
from itertools import tee | |
iterable = [1, 2, 4, 6, 7, 13] | |
for i in tee(iterable, 4): | |
print(list(i)) | |
# OUTPUT | |
""" | |
[1, 2, 4, 6, 7, 13] | |
[1, 2, 4, 6, 7, 13] | |
[1, 2, 4, 6, 7, 13] | |
[1, 2, 4, 6, 7, 13] | |
""" |
fillvalue
. Iteration continues until the longest iterable is exhausted.
from itertools import zip_longest | |
iter1 = [1, 2, 3, 4, 5, 6] | |
iter2 = [1, 4, 9, 16, 25] | |
iter3 = [1, 8, 27, 64, 125] | |
for i in zip_longest(iter1, iter2, iter3, fillvalue = 0): | |
print(i) | |
# OUTPUT | |
""" | |
(1, 1, 1) | |
(2, 4, 8) | |
(3, 9, 27) | |
(4, 16, 64) | |
(5, 25, 125) | |
(6, 0, 0) | |
""" |
These were all the terminating iterators provided by the module. You can clearly see the variety of functionalities that are provided by these iterators. These can be used in your code to make it shorter, more efficient, and also more “pythonic”.
I hope that you found these explanations easy to understand and the examples gave you the hang of it all. As you will go along, you will find more beautiful applications of these functions in solving your problems.
This wraps this article and I’ll come back with the second part of Mastering itertools where we will see the combinatoric iterators along with some more complex examples of all the functions. If you have any suggestions, feedback, or simply want to connect, I’ll be delighted to reach out. You can connect with me on LinkedIn or find some of my work on Github.
Peace.
90+ Python Interview Questions and Answers (202...
10 Jupyter Notebook Tips and Tricks for Beginners
What are Python Iterators and Generators? Progr...
Everything You Should Know about Iterables and ...
Python Generators and Iterators in 2 Minutes fo...
Tutorial – Python List Comprehension With...
Complete Guide to use Loop, xrange and Generato...
Python – Map, Reduce, Filter in 2 Minutes...
Creating a Music Streaming Backend Like Spotify...
A Beginner-Friendly Guide to PyTorch and How it...
We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.
Show details
This site uses cookies to ensure that you get the best experience possible. To learn more about how we use cookies, please refer to our Privacy Policy & Cookies Policy.
It is needed for personalizing the website.
Expiry: Session
Type: HTTP
This cookie is used to prevent Cross-site request forgery (often abbreviated as CSRF) attacks of the website
Expiry: Session
Type: HTTPS
Preserves the login/logout state of users across the whole site.
Expiry: Session
Type: HTTPS
Preserves users' states across page requests.
Expiry: Session
Type: HTTPS
Google One-Tap login adds this g_state cookie to set the user status on how they interact with the One-Tap modal.
Expiry: 365 days
Type: HTTP
Used by Microsoft Clarity, to store and track visits across websites.
Expiry: 1 Year
Type: HTTP
Used by Microsoft Clarity, Persists the Clarity User ID and preferences, unique to that site, on the browser. This ensures that behavior in subsequent visits to the same site will be attributed to the same user ID.
Expiry: 1 Year
Type: HTTP
Used by Microsoft Clarity, Connects multiple page views by a user into a single Clarity session recording.
Expiry: 1 Day
Type: HTTP
Collects user data is specifically adapted to the user or device. The user can also be followed outside of the loaded website, creating a picture of the visitor's behavior.
Expiry: 2 Years
Type: HTTP
Use to measure the use of the website for internal analytics
Expiry: 1 Years
Type: HTTP
The cookie is set by embedded Microsoft Clarity scripts. The purpose of this cookie is for heatmap and session recording.
Expiry: 1 Year
Type: HTTP
Collected user data is specifically adapted to the user or device. The user can also be followed outside of the loaded website, creating a picture of the visitor's behavior.
Expiry: 2 Months
Type: HTTP
This cookie is installed by Google Analytics. The cookie is used to store information of how visitors use a website and helps in creating an analytics report of how the website is doing. The data collected includes the number of visitors, the source where they have come from, and the pages visited in an anonymous form.
Expiry: 399 Days
Type: HTTP
Used by Google Analytics, to store and count pageviews.
Expiry: 399 Days
Type: HTTP
Used by Google Analytics to collect data on the number of times a user has visited the website as well as dates for the first and most recent visit.
Expiry: 1 Day
Type: HTTP
Used to send data to Google Analytics about the visitor's device and behavior. Tracks the visitor across devices and marketing channels.
Expiry: Session
Type: PIXEL
cookies ensure that requests within a browsing session are made by the user, and not by other sites.
Expiry: 6 Months
Type: HTTP
use the cookie when customers want to make a referral from their gmail contacts; it helps auth the gmail account.
Expiry: 2 Years
Type: HTTP
This cookie is set by DoubleClick (which is owned by Google) to determine if the website visitor's browser supports cookies.
Expiry: 1 Year
Type: HTTP
this is used to send push notification using webengage.
Expiry: 1 Year
Type: HTTP
used by webenage to track auth of webenagage.
Expiry: Session
Type: HTTP
Linkedin sets this cookie to registers statistical data on users' behavior on the website for internal analytics.
Expiry: 1 Day
Type: HTTP
Use to maintain an anonymous user session by the server.
Expiry: 1 Year
Type: HTTP
Used as part of the LinkedIn Remember Me feature and is set when a user clicks Remember Me on the device to make it easier for him or her to sign in to that device.
Expiry: 1 Year
Type: HTTP
Used to store information about the time a sync with the lms_analytics cookie took place for users in the Designated Countries.
Expiry: 6 Months
Type: HTTP
Used to store information about the time a sync with the AnalyticsSyncHistory cookie took place for users in the Designated Countries.
Expiry: 6 Months
Type: HTTP
Cookie used for Sign-in with Linkedin and/or to allow for the Linkedin follow feature.
Expiry: 6 Months
Type: HTTP
allow for the Linkedin follow feature.
Expiry: 1 Year
Type: HTTP
often used to identify you, including your name, interests, and previous activity.
Expiry: 2 Months
Type: HTTP
Tracks the time that the previous page took to load
Expiry: Session
Type: HTTP
Used to remember a user's language setting to ensure LinkedIn.com displays in the language selected by the user in their settings
Expiry: Session
Type: HTTP
Tracks percent of page viewed
Expiry: Session
Type: HTTP
Indicates the start of a session for Adobe Experience Cloud
Expiry: Session
Type: HTTP
Provides page name value (URL) for use by Adobe Analytics
Expiry: Session
Type: HTTP
Used to retain and fetch time since last visit in Adobe Analytics
Expiry: 6 Months
Type: HTTP
Remembers a user's display preference/theme setting
Expiry: 6 Months
Type: HTTP
Remembers which users have updated their display / theme preferences
Expiry: 6 Months
Type: HTTP
Used by Google Adsense, to store and track conversions.
Expiry: 3 Months
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
These cookies are used for the purpose of targeted advertising.
Expiry: 6 Hours
Type: HTTP
These cookies are used for the purpose of targeted advertising.
Expiry: 1 Month
Type: HTTP
These cookies are used to gather website statistics, and track conversion rates.
Expiry: 1 Month
Type: HTTP
Aggregate analysis of website visitors
Expiry: 6 Months
Type: HTTP
This cookie is set by Facebook to deliver advertisements when they are on Facebook or a digital platform powered by Facebook advertising after visiting this website.
Expiry: 4 Months
Type: HTTP
Contains a unique browser and user ID, used for targeted advertising.
Expiry: 2 Months
Type: HTTP
Used by LinkedIn to track the use of embedded services.
Expiry: 1 Year
Type: HTTP
Used by LinkedIn for tracking the use of embedded services.
Expiry: 1 Day
Type: HTTP
Used by LinkedIn to track the use of embedded services.
Expiry: 6 Months
Type: HTTP
Use these cookies to assign a unique ID when users visit a website.
Expiry: 6 Months
Type: HTTP
These cookies are set by LinkedIn for advertising purposes, including: tracking visitors so that more relevant ads can be presented, allowing users to use the 'Apply with LinkedIn' or the 'Sign-in with LinkedIn' functions, collecting information about how visitors use the site, etc.
Expiry: 6 Months
Type: HTTP
Used to make a probabilistic match of a user's identity outside the Designated Countries
Expiry: 90 Days
Type: HTTP
Used to collect information for analytics purposes.
Expiry: 1 year
Type: HTTP
Used to store session ID for a users session to ensure that clicks from adverts on the Bing search engine are verified for reporting purposes and for personalisation
Expiry: 1 Day
Type: HTTP
Cookie declaration last updated on 24/03/2023 by Analytics Vidhya.
Cookies are small text files that can be used by websites to make a user's experience more efficient. The law states that we can store cookies on your device if they are strictly necessary for the operation of this site. For all other types of cookies, we need your permission. This site uses different types of cookies. Some cookies are placed by third-party services that appear on our pages. Learn more about who we are, how you can contact us, and how we process personal data in our Privacy Policy.
Edit
Resend OTP
Resend OTP in 45s