-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathitertools_chain.py
More file actions
43 lines (30 loc) · 1.12 KB
/
itertools_chain.py
File metadata and controls
43 lines (30 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# itertools.chain — combine multiple iterables into a single sequence.
#
# chain() lets you iterate through several iterables one after another
# as if they were a single iterable, without building a new list in memory.
from itertools import chain
# --- 1. Chaining different iterables ---
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [True, False]
print('Chained sequence:')
for item in chain(list1, list2, list3):
print(item, end=' ')
print()
# --- 2. Flattening a list of lists ---
# chain(*list_of_lists) unpacks the outer list and chains the inner lists.
list_of_lists = [[1, 2, 3], [4, 5], [6, 7, 8]]
flattened = list(chain(*list_of_lists))
print('\nFlattened:', flattened) # [1, 2, 3, 4, 5, 6, 7, 8]
# --- 3. Memory efficiency ---
# chain() returns a lazy iterator — it does not build a new list.
# Useful when working with large sequences.
large1 = range(1_000_000)
large2 = range(1_000_000)
combined = chain(large1, large2) # no memory allocated for the combined sequence
print('\nFirst 5 of combined large ranges:')
for i, x in enumerate(combined):
if i >= 5:
break
print(x, end=' ')
print()