This tutorial will show you how to join/concatenate/merge iterables in the Python programming language, and provide code examples.
What is an ‘Iterable’ in Python?
An iterable is any kind of Python object that can return each of its members one at a time.
Put simply, it’s any Python object that contains multiple values that can be looped over.
Python’s built-in Iterables include lists, strings, and tuples — all object types which can be represented as a sequence of values.
Iterating over Iterables
To demonstrate this behaviour, we can create a list of strings, and then loop over it, printing each value in the list:
pets = ["duck", "cat", "dog", "hamster"] for pet in pets: print(pet)
Above, a list of pets is defined. As it is a list (defined by the use of square brackets), it is iterable, and can be iterated (looped) over using a for statement.
Concatenating Iterables with itertools.chain()
If you have more than one iterable, and wish to loop over the contents of all of them, you can join them together using the itertools.chain() function
itertools.chain() Function Syntax
The syntax for the itertools.chain() function is as follows:
import itertools itertools.chain(ITERABLE, ITERABLE...)
Note that:
- The itertools library must be imported
- itertools.chain accepts a comma-separated list of ITERABLEs which will be joined/concatenated/merged
- itertools.chain will return a single iterable containing the values from all of the supplied iterables
- They will be in sequential order – the values from the first iterable will be followed by those in the second, and so on
itertools.chain() Examples
Below, two lists of pets are defined. They are then iterated over as a single, merged list using itertools.chain() and a for loop:
import itertools pets = ["duck", "cat", "dog", "hamster"] morePets = ["horse", "parrot", "snake"] for pet in itertools.chain(pets, morePets): print(pet)
You can also assign the results of itertools.chain() to a new variable for reuse:
import itertools pets = ["duck", "cat", "dog", "hamster"] morePets = ["horse", "parrot", "snake"] allPets = itertools.chain(pets, morePets) for pet in allPets: print(pet)