Home > other >  Python list to range
Python list to range

Time:12-26

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)

CodePudding user response:

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]

CodePudding user response:

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]
>>>
  • Related