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.

ExampleEdit & Run
from itertools import chain

L1 = [1, 2, 3]
L2 = ['a', 'b', 'c']

for i in chain(L1, L2):
    print(i)
copy
Output:
1 2 3 a b c [Finished in 0.010906415991485119s]

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.

Syntax:
chain(*iterables)
copy

The iterables parameter represents the arbitrary iterable objects to be linked together for traversal.

Parameters:

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.

ExampleEdit & Run
from itertools import chain

data1 = ['Python', 'Java', 'C++']
data2 = ('Ruby', 'Swift', 'PHP')
data3 = {'Javascript', 'HTML', 'CSS'}

for i in chain(data1, data2, data3):
     print(i)
copy
Output:
Python Java C++ Ruby Swift PHP Javascript HTML CSS [Finished in 0.012317444197833538s]

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.

Syntax:
chain.from_iterable(iterable)
copy

The iterable object  needs to be itself made of iterables otherwise an error will be raised. 

ExampleEdit & Run
from itertools import chain

data = [(1, 2), (3, 4), (5, 6), (7, 8)]

for i in chain.from_iterable(data):
     print(i)
copy
Output:
1 2 3 4 5 6 7 8 [Finished in 0.010930494405329227s]