Python list to range

Question:

I have the list

lst = [3, 5]

How to get a range for each item in the list like this ?

[0, 1, 2, 3]
[0, 1, 2, 3, 4, 5]

This is loop is obviously not working

for i in range(0, lst):
  print(i)
Asked By: hug

||

Answers:

Call range() for each end; to include the end in the range, add 1:

>>> lst = [3, 5]
[3, 5]
>>> ranges = [range(end + 1) for end in lst]
[range(0, 4), range(0, 6)]
>>> for x in ranges:
...     print(list(x))
...
[0, 1, 2, 3]
[0, 1, 2, 3, 4, 5]
>>>
Answered By: AKX
lst = [3, 5]
[list(range(x+1)) for x in lst]
#[[0, 1, 2, 3], [0, 1, 2, 3, 4, 5]]

Or simply:

for x in lst:
    print(list(range(x+1)))
[0, 1, 2, 3]
[0, 1, 2, 3, 4, 5]
Answered By: Talha Tayyab
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.