Sequence unpacking also supports iterators: if you know an iterator will return N elements, you can unpack them into an N-tuple: Built-in functions such as$_{max()}$ and$_{min()}$ can take a single iterator argument and will return the largest or smallest element. The$_{"in"}$ and$_{"not in"}$ operators also support iterators:$_{X in iterator}$ is true if X is found in the stream returned by the iterator. You’ll run into obvious problems if the iterator is infinite;$_{max()}$ ,$_{min()}$ will never return, and if the element X never appears in the stream, the "in" and "not in" operators won’t return either. Note that you can only go forward in an iterator; there’s no way to get the previous element, reset the iterator, or make a copy of it. Iterator objects can optionally provide these additional capabilities, but the iterator protocol only specifies the$_{__next__()}$ method. Functions may therefore consume all of the iterator’s output, and if you need to do something different with the same stream, you’ll have to create a new iterator. We’ve already seen how lists and tuples support iterators. In fact, any Python sequence type, such as strings, will automatically support creation of an iterator. Calling$_{iter()}$ on a dictionary returns an iterator that will loop over the dictionary’s keys: Note that starting with Python 3.7, dictionary iteration order is guaranteed to be the same as the insertion order. In earlier versions, the behaviour was unspecified and could vary between implementations. Applying$_{iter()}$ to a dictionary always loops over the keys, but dictionaries have methods that return other iterators. If you want to iterate over values or key/value pairs, you can explicitly call the$_{values()}$ or$_{items()}$ methods to get an appropriate iterator. The$_{dict()}$ constructor can accept an iterator that returns a finite stream of$_{(key, value)}$ tuples: Files also support iteration by calling the$_{readline()}$ method until there are no more lines in the file. This means you can read each line of a file like this: 5 for line in file: # do something for each line ... >>> L =[('Italy','Rome'), ( 'France','Paris '), ( 'US','Washington DC')] >>> dict(iter(L)) {'Italy': 'Rome', 'France': 'Paris', 'US': 'Washington DC'} >>> m ={ 'Jan':1,'Feb':2,'Mar ':3,'Apr':4,'May ':5,'Jun':6, ... 'Jul':7,'Aug':8,'Sep':9,'Oct':10 ,'Nov':11 ,'Dec':12 } >>>for key in m: ... print(key, m[key]) Jan 1 Feb 2 Mar 3 Apr 4 May 5 Jun 6 Jul 7 Aug 8 Sep 9 Oct 10 Nov 11 Dec 12 >>> L =[1,2,3] >>> iterator =iter(L) >>> a, b, c=iterator >>> a, b, c (1, 2, 3) 2.1 Data Types That Support Iterators