itertools — Functions creating iterators for efficient looping¶
This module implements a number ofiterator building blocks inspiredby constructs from APL, Haskell, and SML. Each has been recast in a formsuitable for Python.
The module standardizes a core set of fast, memory efficient tools that areuseful by themselves or in combination. Together, they form an “iteratoralgebra” making it possible to construct specialized tools succinctly andefficiently in pure Python.
For instance, SML provides a tabulation tool:tabulate(f) which produces asequencef(0),f(1),.... The same effect can be achieved in Pythonby combiningmap() andcount() to formmap(f,count()).
These tools and their built-in counterparts also work well with the high-speedfunctions in theoperator module. For example, the multiplicationoperator can be mapped across two vectors to form an efficient dot-product:sum(map(operator.mul,vector1,vector2)).
Infinite iterators:
Iterator | Arguments | Results | Example |
|---|---|---|---|
start, [step] | start, start+step, start+2*step, … |
| |
p | p0, p1, … plast, p0, p1, … |
| |
elem [,n] | elem, elem, elem, … endlessly or up to n times |
|
Iterators terminating on the shortest input sequence:
Iterator | Arguments | Results | Example |
|---|---|---|---|
p [,func] | p0, p0+p1, p0+p1+p2, … |
| |
p, q, … | p0, p1, … plast, q0, q1, … |
| |
iterable | p0, p1, … plast, q0, q1, … |
| |
data, selectors | (d[0] if s[0]), (d[1] if s[1]), … |
| |
pred, seq | seq[n], seq[n+1], starting when pred fails |
| |
pred, seq | elements of seq where pred(elem) is false |
| |
iterable[, key] | sub-iterators grouped by value of key(v) | ||
seq, [start,] stop [, step] | elements from seq[start:stop:step] |
| |
func, seq | func(*seq[0]), func(*seq[1]), … |
| |
pred, seq | seq[0], seq[1], until pred fails |
| |
it, n | it1, it2, … itn splits one iterator into n | ||
p, q, … | (p[0], q[0]), (p[1], q[1]), … |
|
Combinatoric iterators:
Iterator | Arguments | Results |
|---|---|---|
p, q, … [repeat=1] | cartesian product, equivalent to a nested for-loop | |
p[, r] | r-length tuples, all possible orderings, no repeated elements | |
p, r | r-length tuples, in sorted order, no repeated elements | |
p, r | r-length tuples, in sorted order, with repeated elements |
Examples | Results |
|---|---|
|
|
|
|
|
|
|
|
Itertool functions¶
The following module functions all construct and return iterators. Some providestreams of infinite length, so they should only be accessed by functions orloops that truncate the stream.
itertools.accumulate(iterable[,func,*,initial=None])¶Make an iterator that returns accumulated sums, or accumulatedresults of other binary functions (specified via the optionalfunc argument).
Iffunc is supplied, it should be a functionof two arguments. Elements of the inputiterable may be any typethat can be accepted as arguments tofunc. (For example, withthe default operation of addition, elements may be any addabletype including
DecimalorFraction.)Usually, the number of elements output matches the input iterable.However, if the keyword argumentinitial is provided, theaccumulation leads off with theinitial value so that the outputhas one more element than the input iterable.
Roughly equivalent to:
defaccumulate(iterable,func=operator.add,*,initial=None):'Return running totals'# accumulate([1,2,3,4,5]) --> 1 3 6 10 15# accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120it=iter(iterable)total=initialifinitialisNone:try:total=next(it)exceptStopIteration:returnyieldtotalforelementinit:total=func(total,element)yieldtotal
There are a number of uses for thefunc argument. It can be set to
min()for a running minimum,max()for a running maximum, oroperator.mul()for a running product. Amortization tables can bebuilt by accumulating interest and applying payments. First-orderrecurrence relationscan be modeled by supplying the initial value in the iterable and using onlythe accumulated total infunc argument:>>>data=[3,4,6,2,1,9,0,7,5,8]>>>list(accumulate(data,operator.mul))# running product[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]>>>list(accumulate(data,max))# running maximum[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]# Amortize a 5% loan of 1000 with 4 annual payments of 90>>>cashflows=[1000,-90,-90,-90,-90]>>>list(accumulate(cashflows,lambdabal,pmt:bal*1.05+pmt))[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]# Chaotic recurrence relation https://en.wikipedia.org/wiki/Logistic_map>>>logistic_map=lambdax,_:r*x*(1-x)>>>r=3.8>>>x0=0.4>>>inputs=repeat(x0,36)# only the initial value is used>>>[format(x,'.2f')forxinaccumulate(inputs,logistic_map)]['0.40', '0.91', '0.30', '0.81', '0.60', '0.92', '0.29', '0.79', '0.63', '0.88', '0.39', '0.90', '0.33', '0.84', '0.52', '0.95', '0.18', '0.57', '0.93', '0.25', '0.71', '0.79', '0.63', '0.88', '0.39', '0.91', '0.32', '0.83', '0.54', '0.95', '0.20', '0.60', '0.91', '0.30', '0.80', '0.60']
See
functools.reduce()for a similar function that returns only thefinal accumulated value.New in version 3.2.
Changed in version 3.3:Added the optionalfunc parameter.
Changed in version 3.8:Added the optionalinitial parameter.
itertools.chain(*iterables)¶Make an iterator that returns elements from the first iterable until it isexhausted, then proceeds to the next iterable, until all of the iterables areexhausted. Used for treating consecutive sequences as a single sequence.Roughly equivalent to:
defchain(*iterables):# chain('ABC', 'DEF') --> A B C D E Fforitiniterables:forelementinit:yieldelement
- classmethod
chain.from_iterable(iterable)¶ Alternate constructor for
chain(). Gets chained inputs from asingle iterable argument that is evaluated lazily. Roughly equivalent to:deffrom_iterable(iterables):# chain.from_iterable(['ABC', 'DEF']) --> A B C D E Fforitiniterables:forelementinit:yieldelement
itertools.combinations(iterable,r)¶Returnr length subsequences of elements from the inputiterable.
The combination tuples are emitted in lexicographic ordering according tothe order of the inputiterable. So, if the inputiterable is sorted,the combination tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on theirvalue. So if the input elements are unique, there will be no repeatvalues in each combination.
Roughly equivalent to:
defcombinations(iterable,r):# combinations('ABCD', 2) --> AB AC AD BC BD CD# combinations(range(4), 3) --> 012 013 023 123pool=tuple(iterable)n=len(pool)ifr>n:returnindices=list(range(r))yieldtuple(pool[i]foriinindices)whileTrue:foriinreversed(range(r)):ifindices[i]!=i+n-r:breakelse:returnindices[i]+=1forjinrange(i+1,r):indices[j]=indices[j-1]+1yieldtuple(pool[i]foriinindices)
The code for
combinations()can be also expressed as a subsequenceofpermutations()after filtering entries where the elements are notin sorted order (according to their position in the input pool):defcombinations(iterable,r):pool=tuple(iterable)n=len(pool)forindicesinpermutations(range(n),r):ifsorted(indices)==list(indices):yieldtuple(pool[i]foriinindices)
The number of items returned is
n!/r!/(n-r)!when0<=r<=nor zero whenr>n.
itertools.combinations_with_replacement(iterable,r)¶Returnr length subsequences of elements from the inputiterableallowing individual elements to be repeated more than once.
The combination tuples are emitted in lexicographic ordering according tothe order of the inputiterable. So, if the inputiterable is sorted,the combination tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on theirvalue. So if the input elements are unique, the generated combinationswill also be unique.
Roughly equivalent to:
defcombinations_with_replacement(iterable,r):# combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CCpool=tuple(iterable)n=len(pool)ifnotnandr:returnindices=[0]*ryieldtuple(pool[i]foriinindices)whileTrue:foriinreversed(range(r)):ifindices[i]!=n-1:breakelse:returnindices[i:]=[indices[i]+1]*(r-i)yieldtuple(pool[i]foriinindices)
The code for
combinations_with_replacement()can be also expressed asa subsequence ofproduct()after filtering entries where the elementsare not in sorted order (according to their position in the input pool):defcombinations_with_replacement(iterable,r):pool=tuple(iterable)n=len(pool)forindicesinproduct(range(n),repeat=r):ifsorted(indices)==list(indices):yieldtuple(pool[i]foriinindices)
The number of items returned is
(n+r-1)!/r!/(n-1)!whenn>0.New in version 3.1.
itertools.compress(data,selectors)¶Make an iterator that filters elements fromdata returning only those thathave a corresponding element inselectors that evaluates to
True.Stops when either thedata orselectors iterables has been exhausted.Roughly equivalent to:defcompress(data,selectors):# compress('ABCDEF', [1,0,1,0,1,1]) --> A C E Freturn(dford,sinzip(data,selectors)ifs)
New in version 3.1.
itertools.count(start=0,step=1)¶Make an iterator that returns evenly spaced values starting with numberstart. Oftenused as an argument to
map()to generate consecutive data points.Also, used withzip()to add sequence numbers. Roughly equivalent to:defcount(start=0,step=1):# count(10) --> 10 11 12 13 14 ...# count(2.5, 0.5) -> 2.5 3.0 3.5 ...n=startwhileTrue:yieldnn+=step
When counting with floating point numbers, better accuracy can sometimes beachieved by substituting multiplicative code such as:
(start+step*iforiincount()).Changed in version 3.1:Addedstep argument and allowed non-integer arguments.
itertools.cycle(iterable)¶Make an iterator returning elements from the iterable and saving a copy of each.When the iterable is exhausted, return elements from the saved copy. Repeatsindefinitely. Roughly equivalent to:
defcycle(iterable):# cycle('ABCD') --> A B C D A B C D A B C D ...saved=[]forelementiniterable:yieldelementsaved.append(element)whilesaved:forelementinsaved:yieldelement
Note, this member of the toolkit may require significant auxiliary storage(depending on the length of the iterable).
itertools.dropwhile(predicate,iterable)¶Make an iterator that drops elements from the iterable as long as the predicateis true; afterwards, returns every element. Note, the iterator does not produceany output until the predicate first becomes false, so it may have a lengthystart-up time. Roughly equivalent to:
defdropwhile(predicate,iterable):# dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1iterable=iter(iterable)forxiniterable:ifnotpredicate(x):yieldxbreakforxiniterable:yieldx
itertools.filterfalse(predicate,iterable)¶Make an iterator that filters elements from iterable returning only those forwhich the predicate is
False. Ifpredicate isNone, return the itemsthat are false. Roughly equivalent to:deffilterfalse(predicate,iterable):# filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8ifpredicateisNone:predicate=boolforxiniterable:ifnotpredicate(x):yieldx
itertools.groupby(iterable,key=None)¶Make an iterator that returns consecutive keys and groups from theiterable.Thekey is a function computing a key value for each element. If notspecified or is
None,key defaults to an identity function and returnsthe element unchanged. Generally, the iterable needs to already be sorted onthe same key function.The operation of
groupby()is similar to theuniqfilter in Unix. Itgenerates a break or new group every time the value of the key function changes(which is why it is usually necessary to have sorted the data using the same keyfunction). That behavior differs from SQL’s GROUP BY which aggregates commonelements regardless of their input order.The returned group is itself an iterator that shares the underlying iterablewith
groupby(). Because the source is shared, when thegroupby()object is advanced, the previous group is no longer visible. So, if that datais needed later, it should be stored as a list:groups=[]uniquekeys=[]data=sorted(data,key=keyfunc)fork,gingroupby(data,keyfunc):groups.append(list(g))# Store group iterator as a listuniquekeys.append(k)
groupby()is roughly equivalent to:classgroupby:# [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B# [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC Ddef__init__(self,iterable,key=None):ifkeyisNone:key=lambdax:xself.keyfunc=keyself.it=iter(iterable)self.tgtkey=self.currkey=self.currvalue=object()def__iter__(self):returnselfdef__next__(self):self.id=object()whileself.currkey==self.tgtkey:self.currvalue=next(self.it)# Exit on StopIterationself.currkey=self.keyfunc(self.currvalue)self.tgtkey=self.currkeyreturn(self.currkey,self._grouper(self.tgtkey,self.id))def_grouper(self,tgtkey,id):whileself.idisidandself.currkey==tgtkey:yieldself.currvaluetry:self.currvalue=next(self.it)exceptStopIteration:returnself.currkey=self.keyfunc(self.currvalue)
itertools.islice(iterable,stop)¶itertools.islice(iterable,start,stop[,step])Make an iterator that returns selected elements from the iterable. Ifstart isnon-zero, then elements from the iterable are skipped until start is reached.Afterward, elements are returned consecutively unlessstep is set higher thanone which results in items being skipped. Ifstop is
None, then iterationcontinues until the iterator is exhausted, if at all; otherwise, it stops at thespecified position. Unlike regular slicing,islice()does not supportnegative values forstart,stop, orstep. Can be used to extract relatedfields from data where the internal structure has been flattened (for example, amulti-line report may list a name field on every third line). Roughly equivalent to:defislice(iterable,*args):# islice('ABCDEFG', 2) --> A B# islice('ABCDEFG', 2, 4) --> C D# islice('ABCDEFG', 2, None) --> C D E F G# islice('ABCDEFG', 0, None, 2) --> A C E Gs=slice(*args)start,stop,step=s.startor0,s.stoporsys.maxsize,s.stepor1it=iter(range(start,stop,step))try:nexti=next(it)exceptStopIteration:# Consume *iterable* up to the *start* position.fori,elementinzip(range(start),iterable):passreturntry:fori,elementinenumerate(iterable):ifi==nexti:yieldelementnexti=next(it)exceptStopIteration:# Consume to *stop*.fori,elementinzip(range(i+1,stop),iterable):pass
Ifstart is
None, then iteration starts at zero. Ifstep isNone,then the step defaults to one.
itertools.permutations(iterable,r=None)¶Return successiver length permutations of elements in theiterable.
Ifr is not specified or is
None, thenr defaults to the lengthof theiterable and all possible full-length permutationsare generated.The permutation tuples are emitted in lexicographic ordering according tothe order of the inputiterable. So, if the inputiterable is sorted,the combination tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on theirvalue. So if the input elements are unique, there will be no repeatvalues in each permutation.
Roughly equivalent to:
defpermutations(iterable,r=None):# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC# permutations(range(3)) --> 012 021 102 120 201 210pool=tuple(iterable)n=len(pool)r=nifrisNoneelserifr>n:returnindices=list(range(n))cycles=list(range(n,n-r,-1))yieldtuple(pool[i]foriinindices[:r])whilen:foriinreversed(range(r)):cycles[i]-=1ifcycles[i]==0:indices[i:]=indices[i+1:]+indices[i:i+1]cycles[i]=n-ielse:j=cycles[i]indices[i],indices[-j]=indices[-j],indices[i]yieldtuple(pool[i]foriinindices[:r])breakelse:return
The code for
permutations()can be also expressed as a subsequence ofproduct(), filtered to exclude entries with repeated elements (thosefrom the same position in the input pool):defpermutations(iterable,r=None):pool=tuple(iterable)n=len(pool)r=nifrisNoneelserforindicesinproduct(range(n),repeat=r):iflen(set(indices))==r:yieldtuple(pool[i]foriinindices)
The number of items returned is
n!/(n-r)!when0<=r<=nor zero whenr>n.
itertools.product(*iterables,repeat=1)¶Cartesian product of input iterables.
Roughly equivalent to nested for-loops in a generator expression. For example,
product(A,B)returns the same as((x,y)forxinAforyinB).The nested loops cycle like an odometer with the rightmost element advancingon every iteration. This pattern creates a lexicographic ordering so that ifthe input’s iterables are sorted, the product tuples are emitted in sortedorder.
To compute the product of an iterable with itself, specify the number ofrepetitions with the optionalrepeat keyword argument. For example,
product(A,repeat=4)means the same asproduct(A,A,A,A).This function is roughly equivalent to the following code, except that theactual implementation does not build up intermediate results in memory:
defproduct(*args,repeat=1):# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111pools=[tuple(pool)forpoolinargs]*repeatresult=[[]]forpoolinpools:result=[x+[y]forxinresultforyinpool]forprodinresult:yieldtuple(prod)
itertools.repeat(object[,times])¶Make an iterator that returnsobject over and over again. Runs indefinitelyunless thetimes argument is specified. Used as argument to
map()forinvariant parameters to the called function. Also used withzip()tocreate an invariant part of a tuple record.Roughly equivalent to:
defrepeat(object,times=None):# repeat(10, 3) --> 10 10 10iftimesisNone:whileTrue:yieldobjectelse:foriinrange(times):yieldobject
A common use forrepeat is to supply a stream of constant values tomaporzip:
>>>list(map(pow,range(10),repeat(2)))[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
itertools.starmap(function,iterable)¶Make an iterator that computes the function using arguments obtained fromthe iterable. Used instead of
map()when argument parameters are alreadygrouped in tuples from a single iterable (the data has been “pre-zipped”). Thedifference betweenmap()andstarmap()parallels the distinctionbetweenfunction(a,b)andfunction(*c). Roughly equivalent to:defstarmap(function,iterable):# starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000forargsiniterable:yieldfunction(*args)
itertools.takewhile(predicate,iterable)¶Make an iterator that returns elements from the iterable as long as thepredicate is true. Roughly equivalent to:
deftakewhile(predicate,iterable):# takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4forxiniterable:ifpredicate(x):yieldxelse:break
itertools.tee(iterable,n=2)¶Returnn independent iterators from a single iterable.
The following Python code helps explain whattee does (although the actualimplementation is more complex and uses only a single underlyingFIFO queue).
Roughly equivalent to:
deftee(iterable,n=2):it=iter(iterable)deques=[collections.deque()foriinrange(n)]defgen(mydeque):whileTrue:ifnotmydeque:# when the local deque is emptytry:newval=next(it)# fetch a new value andexceptStopIteration:returnfordindeques:# load it to all the dequesd.append(newval)yieldmydeque.popleft()returntuple(gen(d)fordindeques)
Once
tee()has made a split, the originaliterable should not beused anywhere else; otherwise, theiterable could get advanced withoutthe tee objects being informed.teeiterators are not threadsafe. ARuntimeErrormay beraised when using simultaneously iterators returned by the sametee()call, even if the originaliterable is threadsafe.This itertool may require significant auxiliary storage (depending on howmuch temporary data needs to be stored). In general, if one iterator usesmost or all of the data before another iterator starts, it is faster to use
list()instead oftee().
itertools.zip_longest(*iterables,fillvalue=None)¶Make an iterator that aggregates elements from each of the iterables. If theiterables are of uneven length, missing values are filled-in withfillvalue.Iteration continues until the longest iterable is exhausted. Roughly equivalent to:
defzip_longest(*args,fillvalue=None):# zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-iterators=[iter(it)foritinargs]num_active=len(iterators)ifnotnum_active:returnwhileTrue:values=[]fori,itinenumerate(iterators):try:value=next(it)exceptStopIteration:num_active-=1ifnotnum_active:returniterators[i]=repeat(fillvalue)value=fillvaluevalues.append(value)yieldtuple(values)
If one of the iterables is potentially infinite, then the
zip_longest()function should be wrapped with something that limits the number of calls(for exampleislice()ortakewhile()). If not specified,fillvalue defaults toNone.
Itertools Recipes¶
This section shows recipes for creating an extended toolset using the existingitertools as building blocks.
Substantially all of these recipes and many, many others can be installed fromthemore-itertools project foundon the Python Package Index:
pipinstallmore-itertools
The extended tools offer the same high performance as the underlying toolset.The superior memory performance is kept by processing elements one at a timerather than bringing the whole iterable into memory all at once. Code volume iskept small by linking the tools together in a functional style which helpseliminate temporary variables. High speed is retained by preferring“vectorized” building blocks over the use of for-loops andgeneratorswhich incur interpreter overhead.
deftake(n,iterable):"Return first n items of the iterable as a list"returnlist(islice(iterable,n))defprepend(value,iterator):"Prepend a single value in front of an iterator"# prepend(1, [2, 3, 4]) -> 1 2 3 4returnchain([value],iterator)deftabulate(function,start=0):"Return function(0), function(1), ..."returnmap(function,count(start))deftail(n,iterable):"Return an iterator over the last n items"# tail(3, 'ABCDEFG') --> E F Greturniter(collections.deque(iterable,maxlen=n))defconsume(iterator,n=None):"Advance the iterator n-steps ahead. If n is None, consume entirely."# Use functions that consume iterators at C speed.ifnisNone:# feed the entire iterator into a zero-length dequecollections.deque(iterator,maxlen=0)else:# advance to the empty slice starting at position nnext(islice(iterator,n,n),None)defnth(iterable,n,default=None):"Returns the nth item or a default value"returnnext(islice(iterable,n,None),default)defall_equal(iterable):"Returns True if all the elements are equal to each other"g=groupby(iterable)returnnext(g,True)andnotnext(g,False)defquantify(iterable,pred=bool):"Count how many times the predicate is true"returnsum(map(pred,iterable))defpadnone(iterable):"""Returns the sequence elements and then returns None indefinitely. Useful for emulating the behavior of the built-in map() function. """returnchain(iterable,repeat(None))defncycles(iterable,n):"Returns the sequence elements n times"returnchain.from_iterable(repeat(tuple(iterable),n))defdotproduct(vec1,vec2):returnsum(map(operator.mul,vec1,vec2))defflatten(list_of_lists):"Flatten one level of nesting"returnchain.from_iterable(list_of_lists)defrepeatfunc(func,times=None,*args):"""Repeat calls to func with specified arguments. Example: repeatfunc(random.random) """iftimesisNone:returnstarmap(func,repeat(args))returnstarmap(func,repeat(args,times))defpairwise(iterable):"s -> (s0,s1), (s1,s2), (s2, s3), ..."a,b=tee(iterable)next(b,None)returnzip(a,b)defgrouper(iterable,n,fillvalue=None):"Collect data into fixed-length chunks or blocks"# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"args=[iter(iterable)]*nreturnzip_longest(*args,fillvalue=fillvalue)defroundrobin(*iterables):"roundrobin('ABC', 'D', 'EF') --> A D E B F C"# Recipe credited to George Sakkisnum_active=len(iterables)nexts=cycle(iter(it).__next__foritiniterables)whilenum_active:try:fornextinnexts:yieldnext()exceptStopIteration:# Remove the iterator we just exhausted from the cycle.num_active-=1nexts=cycle(islice(nexts,num_active))defpartition(pred,iterable):'Use a predicate to partition entries into false entries and true entries'# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9t1,t2=tee(iterable)returnfilterfalse(pred,t1),filter(pred,t2)defpowerset(iterable):"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"s=list(iterable)returnchain.from_iterable(combinations(s,r)forrinrange(len(s)+1))defunique_everseen(iterable,key=None):"List unique elements, preserving order. Remember all elements ever seen."# unique_everseen('AAAABBBCCDAABBB') --> A B C D# unique_everseen('ABBCcAD', str.lower) --> A B C Dseen=set()seen_add=seen.addifkeyisNone:forelementinfilterfalse(seen.__contains__,iterable):seen_add(element)yieldelementelse:forelementiniterable:k=key(element)ifknotinseen:seen_add(k)yieldelementdefunique_justseen(iterable,key=None):"List unique elements, preserving order. Remember only the element just seen."# unique_justseen('AAAABBBCCDAABBB') --> A B C D A B# unique_justseen('ABBCcAD', str.lower) --> A B C A Dreturnmap(next,map(operator.itemgetter(1),groupby(iterable,key)))defiter_except(func,exception,first=None):""" Call a function repeatedly until an exception is raised. Converts a call-until-exception interface to an iterator interface. Like builtins.iter(func, sentinel) but uses an exception instead of a sentinel to end the loop. Examples: iter_except(functools.partial(heappop, h), IndexError) # priority queue iterator iter_except(d.popitem, KeyError) # non-blocking dict iterator iter_except(d.popleft, IndexError) # non-blocking deque iterator iter_except(q.get_nowait, Queue.Empty) # loop over a producer Queue iter_except(s.pop, KeyError) # non-blocking set iterator """try:iffirstisnotNone:yieldfirst()# For database APIs needing an initial cast to db.first()whileTrue:yieldfunc()exceptexception:passdeffirst_true(iterable,default=False,pred=None):"""Returns the first true value in the iterable. If no true value is found, returns *default* If *pred* is not None, returns the first item for which pred(item) is true. """# first_true([a,b,c], x) --> a or b or c or x# first_true([a,b], x, f) --> a if f(a) else b if f(b) else xreturnnext(filter(pred,iterable),default)defrandom_product(*args,repeat=1):"Random selection from itertools.product(*args, **kwds)"pools=[tuple(pool)forpoolinargs]*repeatreturntuple(random.choice(pool)forpoolinpools)defrandom_permutation(iterable,r=None):"Random selection from itertools.permutations(iterable, r)"pool=tuple(iterable)r=len(pool)ifrisNoneelserreturntuple(random.sample(pool,r))defrandom_combination(iterable,r):"Random selection from itertools.combinations(iterable, r)"pool=tuple(iterable)n=len(pool)indices=sorted(random.sample(range(n),r))returntuple(pool[i]foriinindices)defrandom_combination_with_replacement(iterable,r):"Random selection from itertools.combinations_with_replacement(iterable, r)"pool=tuple(iterable)n=len(pool)indices=sorted(random.randrange(n)foriinrange(r))returntuple(pool[i]foriinindices)defnth_combination(iterable,r,index):'Equivalent to list(combinations(iterable, r))[index]'pool=tuple(iterable)n=len(pool)ifr<0orr>n:raiseValueErrorc=1k=min(r,n-r)foriinrange(1,k+1):c=c*(n-k+i)//iifindex<0:index+=cifindex<0orindex>=c:raiseIndexErrorresult=[]whiler:c,n,r=c*r//n,n-1,r-1whileindex>=c:index-=cc,n=c*(n-r)//n,n-1result.append(pool[-1-n])returntuple(result)