How to Merge Multiple Iterables with a Generator in Python

This code defines a generator function that 'chains' or merges multiple iterables into a single iterator, which is then converted to a list.

Easy Python 3.0+ Aug 9, 2026 Comprehensions & generators 12 views 0 copies

Python code

15 lines
Python 3.0+
def chain(*iterables):
    for iterable in iterables:
        yield from iterable

def main():
    list1 = [1, 2, 3]
    tuple1 = (4, 5)
    set1 = {6, 7}
    string1 = "89"

    result = list(chain(list1, tuple1, set1, string1))
    print(result)

if __name__ == "__main__":
    main()

Output

stdout
[1, 2, 3, 4, 5, 6, 7, '8', '9']

How it works

The chain function uses yield from to delegate iteration to each iterable in order. This is memory-efficient because it yields elements one at a time without creating a new container. The *iterables parameter allows passing any number of iterables. The main function demonstrates chaining a list, tuple, set, and string, converting the generator to a list to display the merged sequence.

Common mistakes

  • Using `yield from` outside a generator function, which raises SyntaxError.
  • Assuming iterables are in order when sets, which are unordered, are passed.
  • Forgetting to convert the generator result to a list or other container before printing, which shows a generator object.
  • Including non-iterable arguments, which raises TypeError at runtime.

Variations

  1. Use `itertools.chain` from the standard library instead of defining a custom generator: `list(itertools.chain(list1, tuple1, set1, string1))`.
  2. Use a list comprehension with nested loops to flatten multiple iterables into a list, though less memory-efficient.

Real-world use cases

  • Flattening multiple database query result sets into a single iterator for processing without loading all results into memory.
  • Combining log entries from multiple files or streams into one unified sequence for analysis or reporting.
  • Merging several data source iterables (CSV rows, API responses) into a single feed for a data pipeline.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.