Skip to content

Commit

Permalink
upd leetcode.md
Browse files Browse the repository at this point in the history
  • Loading branch information
halyph committed Dec 15, 2023
1 parent 55e8e86 commit 537c299
Showing 1 changed file with 50 additions and 44 deletions.
94 changes: 50 additions & 44 deletions docs/wiki/misc/leetcode.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,47 +106,53 @@ Variable | Meaning

### Initialize List

We can create a list through `*` operator if the item in the list expression is an immutable object.

```python
>>> a = [None] * 3
>>> a
[None, None, None]
>>> a[0] = "foo"
>>> a
['foo', None, None]
```

However, if the item in the list expression is a **mutable** object, the `*` operator will copy the reference of the item `N` times (i.e. *all objects in the list point to the same address*). In order to avoid this pitfall, we should use a list comprehension to initialize a list:


```python
>>> a = [[]] * 3
>>> b = [[] for _ in range(3)]
>>> a[0].append("Hello")
>>> a
[['Hello'], ['Hello'], ['Hello']]
>>> b[0].append("Python")
>>> b
[['Python'], [], []]
```

### Initialize Matrix (List of Lists)

```python
>>> rows = 2
>>> cols = 3
>>> [[0] * cols for _ in range(rows)]
[[0, 0, 0], [0, 0, 0]]
```

Again, DON'T do this

```python
>>> a = [[0] * 3] * 3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[1][1] = 2
>>> a
[[0, 2, 0], [0, 2, 0], [0, 2, 0]]
```
Initialize | How
-|-
List | `[None] * size`
Matrix | `[[0] * cols for _ in range(rows)]`

??? warning

We can create a list through `*` operator if the item in the list expression is an immutable object.

```python
>>> a = [None] * 3
>>> a
[None, None, None]
>>> a[0] = "foo"
>>> a
['foo', None, None]
```

However, if the item in the list expression is a **mutable** object, the `*` operator will copy the reference of the item `N` times (i.e. *all objects in the list point to the same address*). In order to avoid this pitfall, we should use a list comprehension to initialize a list:

```python
>>> a = [[]] * 3
>>> b = [[] for _ in range(3)]
>>> a[0].append("Hello")
>>> a
[['Hello'], ['Hello'], ['Hello']]
>>> b[0].append("Python")
>>> b
[['Python'], [], []]
```

**Initialize Matrix (List of Lists)**

```python
>>> rows = 2
>>> cols = 3
>>> [[0] * cols for _ in range(rows)]
[[0, 0, 0], [0, 0, 0]]
```

Again, DON'T do this

```python
>>> a = [[0] * 3] * 3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[1][1] = 2
>>> a
[[0, 2, 0], [0, 2, 0], [0, 2, 0]]
```

0 comments on commit 537c299

Please sign in to comment.