I want to create a continuous arithmetic progression as a list of lists.
I came up with this solution:
def foo(start: int = 1, end: int = 20, step: int = 4) -> list:
"""Return arithmetic progression as LoL."""
p = []
for i in range(start, end, step):
a = []
for x in range(i, i+step):
a.append(x)
p.append(a)
return p
>>> foo()
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]
How pythonic is this approach? Are there more efficient ways to implement this? I assume this could be refactored with a list comprehension. Any other suggestions?
Your solution is fine, but this would be the list comprehension way
def foo(start: int = 1, end: int = 20, step: int = 4) -> list:
"""Return arithmetic progression as LoL."""
return [list(range(i, i+step)) for i in range(start, end, step)]
It's not any more efficient, so focus on readability