The chain()
function in the itertools
module provides a Pythonic way for successively traversing through multiple iterable objects as if it was one long sequence.
The above approach is different and more efficient than concatenating the two lists then looping over the resulting list. This is because the chain function actually creates an iterator objects which itself does not hold any value but rather acts as a tool for looping over the elements of each of the lists. This approach is more efficient in terms of both memory usage and time taken for the program to execute.
chain(*iterables)
copy
The iterables
parameter represents the arbitrary iterable objects to be linked together for traversal.
The function returns an iterator object which traverses through the elements of the first iterable until it is exhausted, then moves to the next iterable, and so on until all elements are exhausted.
The from_iterable() method
The chain
class have the from_iterable()
class method which can be used to create a chain
object from a two dimensional iterable.
chain.from_iterable(iterable)
copy
The iterable
object needs to be itself made of iterables otherwise an error will be raised.