1. from itertools import chain
    2. x = [1, 2, 3, 4]
    3. y = ['x', 'y', 'z']
    4. for x in chain(x, y):
    5. print(x)
    1. >>> 1234xyz

    使用 + 合并两个列表时, 会在内存中生成一个新列表, 当列表非常大时, 内存有一定开销, 并且 + 无法合并不同类型的容器, 使用 chain 很好的解决了这两点.

    1. >>> import heapq
    2. >>> a = [1, 4, 7, 10]
    3. >>> b = [2, 5, 6, 11]
    4. >>> for c in heapq.merge(a, b):
    5. ... print(c)
    6. ...
    7. 1
    8. 2
    9. 4
    10. 5
    11. 6
    12. 7
    13. 10
    14. 11

    heapq.merge() 会将列表进行排序, 并不会立即读取列表.