Ask Your Question

Revision history [back]

In general, one may prefer to use iterators instead of lists, because the creation of the list takes time and is not necessary:

sage: %time for i in list(range(100000000)): print(i); break
0
CPU times: user 1.56 s, sys: 1.06 s, total: 2.63 s
Wall time: 2.62 s
sage: %time for i in iter(range(100000000)): print(i); break
0
CPU times: user 25 µs, sys: 1e+03 ns, total: 26 µs
Wall time: 116 µs

Also since Python 3, range is an iterator by default:

sage: %time for i in range(100000000): print(i); break
0
CPU times: user 29 µs, sys: 1e+03 ns, total: 30 µs
Wall time: 34.1 µs

In the particular problem asked here, one may use iterators provided by the Python itertools:

sage: import itertools
sage: T = itertools.product((0,1), repeat=4)
sage: C = itertools.combinations(T, 5)
sage: %time for c in C: print(c); break
((0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0))
CPU times: user 24 µs, sys: 1 µs, total: 25 µs
Wall time: 27.4 µs