Skip to content

Commit 8ddf076

Browse files
committed
Show sequence iteration anti-pattern
1 parent 2fa01ab commit 8ddf076

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

04 More on Variables/5 Two remarks about iteration over sequences Item numbering in a loop.md renamed to 04 More on Variables/5 Three remarks about iteration over sequences.md

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,30 @@ grand_parent: Programming for Modelling and Data Analysis
44
nav_order: 5
55
---
66

7-
# Two remarks about iteration over sequences
7+
# Three remarks about iteration over sequences
8+
9+
## Correctly iterating over sequences
10+
11+
When iterating over a sequence, you may be tempted to use something like:
12+
13+
<div style="text-decoration: line-through;" onmouseover="this.style.textDecoration='none'" onmouseout="this.style.textDecoration='line-through'" markdown="1">
14+
15+
```python
16+
for i in range(len(sequence)):
17+
element = sequence[i]
18+
operate on element
19+
```
20+
21+
</div>
22+
23+
This is particularly common for people who have some experience with different programming languages, like C++. **In Python this is wrong!** Instead, you should simply iterate over sequence elements disregarding their indices:
24+
25+
```python
26+
for element in sequence:
27+
operate on element
28+
```
29+
30+
This is much more elegant and works also with sequences that are not indexed with numbers, like dictionaries or sets.
831

932
## Item numbering in a loop
1033

@@ -37,7 +60,7 @@ for element1, element2, element3 in zip(sequence1, sequence2, sequence3):
3760
loop block
3861
```
3962

40-
For exaple:
63+
For example:
4164

4265
```python
4366
first_names = ["Harry", "Frodo", "James"]

index.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ has_toc: false
4141
* [Lists](04%20More%20on%20Variables/2%20Lists)
4242
* [Dictionaries](04%20More%20on%20Variables/3%20Dictionaries)
4343
* [Sets](04%20More%20on%20Variables/4%20Sets)
44-
* [Two remarks about iteration over sequences Item numbering in a loop](04%20More%20on%20Variables/5%20Two%20remarks%20about%20iteration%20over%20sequences%20Item%20numbering%20in%20a%20loop)
44+
* [Three remarks about iteration over sequences](04%20More%20on%20Variables/5%20Three%20remarks%20about%20iteration%20over%20sequences)
4545
* [Complex numbers](04%20More%20on%20Variables/6%20Complex%20numbers)
4646
* [String operations](04%20More%20on%20Variables/7%20String%20operations)
4747
* [Variables and variable types](04%20More%20on%20Variables/8%20Variables%20and%20variable%20types)

0 commit comments

Comments
 (0)