Search code examples
pythonlistfor-loopunpack

How to unpack all values in a range of list


So, I hope it is quite easy but can't realize it in a compact way.

The idea is that you have 2 numbers, that create a range, like: range = [-3,2], and we want to create a tuple or list, no matter, with all values in this range: new_range = [-3, -2, -1, 0, 1, 2].

How can this code be implemented to not lose last number:

range = [-3,2]
new_range = []
for i in range(*range):
   new_range.append(_) 

print(new_range) result is: new_range = [-3, -2, -1, 0, 1]

Is it possible not to lose last number withoud implementation of more multiline code? Cause actule we can add smth like: new_range.append(new_range[len(new_range)-1] + 1) but it looks terrible as for me


Solution

  • From comments:

    my_range = [-3,2]   #we camt use 'range' word as variable cause it is name of the function
    new_range = []
    for i in range(my_range[0], my_range[1] + 1):
       new_range.append(_) 
    
    print(new_range) result is: new_range = [-3, -2, -1, 0, 1, 2]