gh-38323: some fixes for ruff code C41 (about loops and iteration)
a few minor code fixes in various places, about a better use of loops
https://docs.astral.sh/ruff/rules/#flake8-comprehensions-c4
### :memo: Checklist
- [x] The title is concise and informative.
- [x] The description explains in detail what this PR is about.
URL: https://github.com/sagemath/sage/pull/38323
Reported by: Frédéric Chapoton
Reviewer(s): Frédéric Chapoton, Matthias Köppe