-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlist_comprehensions.py
More file actions
57 lines (40 loc) · 1.36 KB
/
Copy pathlist_comprehensions.py
File metadata and controls
57 lines (40 loc) · 1.36 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# List comprehensions — concise syntax for building lists.
#
# Also demonstrates a common pitfall with 2D list initialisation
# using multiplication vs comprehension.
from random import seed, random
seed(42)
# --- 1. List comprehension with nested loops ---
# Build a 10x10 grid, randomly setting cells to 1 with 30% probability.
size = 10
density = 0.3
grid = [[0 for _ in range(size)] for _ in range(size)]
for i in range(size):
for j in range(size):
if random() < density:
grid[i][j] = 1
print('Random grid (30% density):')
for row in grid:
print(row)
# --- 2. The shared-reference pitfall ---
# [[0] * 3] * 2 does NOT create two independent rows.
# Both rows are the same list object in memory.
# Modifying one modifies both.
print('\nShared reference pitfall:')
L = [[0] * 3] * 2
print(L) # [[0, 0, 0], [0, 0, 0]]
L[0][1] = 10
print(L) # [[0, 10, 0], [0, 10, 0]] — both rows changed!
# --- 3. Correct 2D list with comprehension ---
# Each row is a distinct list object.
print('\nCorrect 2D list using comprehension:')
L = [[0] * 3 for _ in range(2)]
print(L) # [[0, 0, 0], [0, 0, 0]]
L[0][1] = 10
print(L) # [[0, 10, 0], [0, 0, 0]] — only first row changed
# --- 4. Simple 1D list creation ---
N = 5
ar = [0] * N
print(f'\n[0] * {N}: {ar}')
arr = [0 for _ in range(N)]
print(f'Comprehension: {arr}')