Maciej Radwański
Maciej Radwański

Reputation: 9

Range list for every item in list loop

I'm trying to create a list of ranges from a flat list of numbers. It's working when it's looping via simple range but when trying to loop a custom list its giving empty sublists. I just started my python adventure, don't be cruel ;) Any help would be very greatly appreciated.

Expected output is from list [0, 1, 2] -> [[0], [0, 1], [0, 1, 2]]

a = [1,2]
b = []

def makerange(n):
    b.append(list(range(0, n, 1)))

for a in range(10):
    makerange(a)

print(b)

[[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7, 8]]

Upvotes: 0

Views: 78

Answers (3)

Scott Boston
Scott Boston

Reputation: 153460

Use slicing in case your list isn't integers:

  • Case 1:

With strings

l = [*'ABCDEF']
[l[:n+1] for n in range(len(l))]

Output:

[['A'],
 ['A', 'B'],
 ['A', 'B', 'C'],
 ['A', 'B', 'C', 'D'],
 ['A', 'B', 'C', 'D', 'E'],
 ['A', 'B', 'C', 'D', 'E', 'F']]
  • Case 2:

And with l = [0,1,2]

l = [0,1,2]
[l[:n+1] for n in range(len(l))]

Output:

[[0], [0, 1], [0, 1, 2]]
  • Case 3

Or list of integers are in non ascending order:

l = [2,1,0]
[l[:n+1] for n in range(len(l))]

Output:

[[2], [2, 1], [2, 1, 0]]

Upvotes: 0

Patrick Artner
Patrick Artner

Reputation: 51643

It is safer to keep the colleting list inside the function and return it from the function:

def multiranges(data):
    rv = []
    for p in data:
        rv.append(list(range(p+1)))
    return rv

print(multiranges([0,1,2]))

Output:

[[0],[0,1],[0,1,2]]

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

Don't overcomplicate this:

>>> a = [0,1,2]
>>> [list(range(n+1)) for n in a]
[[0], [0, 1], [0, 1, 2]]

Adding 1 to range endpoint to include the end value.

Upvotes: 3

Related Questions