KKAIROS
Practical guideIllustrative3 min read

Python enumerate, zip and range: loop with an index or two lists

enumerate adds indexes, zip pairs iterables, range generates numbers. zip stops at the shortest; range excludes its stop; enumerate takes a start.

Published:

Updated:

Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.

TE-53-A: zip stops at the shortest iterable, range excludes stop, enumerate accepts a start

No setup needed: the command below creates what it uses in the throwaway folder.

Command:

python3 -c "print(list(zip([1,2,3],'ab')), list(range(1,4)), list(enumerate('ab', start=1)))"

Recorded output:

[(1, 'a'), (2, 'b')] [1, 2, 3] [(1, 'a'), (2, 'b')]

TE-53-B: zip of two strings, range with a negative step, and enumerate of an empty list

Setup for this run, inside a throwaway directory (mktemp -d):

cat > s.py <<'EOS'
print(list(zip('ab', 'xyz')))
print(list(range(5, 0, -2)))
print(list(enumerate([])))
EOS

Command:

python3 s.py

Recorded output:

[('a', 'x'), ('b', 'y')]
[5, 3, 1]
[]

Exit status: 0. This status and the output match what was written before the run.

TE-53-C: expected non-zero exit: range with a float raises TypeError

Setup for this run, inside a throwaway directory (mktemp -d):

cat > s.py <<'EOS'
range(1.5)
EOS

Command:

python3 s.py

Recorded output: none, standard output was empty.

Standard error from the same run:

Traceback (most recent call last):
  File "/tmp/b21-ou58rtkn/work/s.py", line 1, in <module>
    range(1.5)
TypeError: 'float' object cannot be interpreted as an integer

Exit status: 1. This status and the output match what was written before the run. The path in the traceback line is a temporary folder and differs on each machine and each run.

TE-53-B: zip of 'ab' and 'xyz' stopped at the shorter input, range(5, 0, -2) gave [5, 3, 1], and enumerate of an empty list gave []. TE-53-C: range(1.5) stopped with exit status 1. The last line of standard error is TypeError: 'float' object cannot be interpreted as an integer.

Limits

zip stops at the shortest; range excludes its stop; enumerate takes a start.

Ad

Source

Evidence

Evidence table

| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-53-A | zip stops at the shortest iterable, range excludes stop, enumerate accepts a start | 0 | PASS | 944bc21dffb2 | | TE-53-B | zip of two strings, range with a negative step, and enumerate of an empty list | 0 | PASS | a4cc79ad7659 | | TE-53-C | expected non-zero exit: range with a float raises TypeError | 1 | PASS | 9251caf79948 |

Every row has a recorded log holding the setup commands, the command, stdout, stderr, exit status and the final directory state. The first 12 characters of the log's sha256 are in the table.

All full guides: All guides