Reputation: 1865
How can I create a list that will have a starting value and length of the list. For example, if I wanted to make a list starting at 17 that was of length 5:
num_list = [17, 18, 19, 20, 21]
I have tried the following however it is not producing the correct results
def answer(start, length):
id_arr = list(range(start, length))
print(id_arr)
answer(17, 10)
Output: []
And I understand the reason for this because, the starting value, in this case, is 17, however, it is trying to end at value 10 thus creating an empty list so how can I make the value of length
be the size of the list and not the ending value of the list?
Upvotes: 6
Views: 38361
Reputation: 31
in your def
id_arr = list(range(start, start+length))
should give you the desired result
Upvotes: 3
Reputation: 4330
The built-in range function in Python is very useful to generate sequences of numbers in the form of a list. If we provide two parameters in range The first one is starting point, and second one is end point. The given end point is never part of the generated list. So we can use this method:
def answer(start, length):
id_arr = [list_items for list_items in range(start, start + length)]
print id_arr
answer (17, 5)
>> [17, 18, 19, 20, 21]
Upvotes: 1
Reputation: 6762
range function itself does all that for you.
range(starting value, endvalue+1, step)
so you can go for range(17,22)
If you writing custom function then go for:
def answer(start, length):
id_arr = list(range(start, start+length))
print(id_arr)
answer(17, 5)
output :
[17, 18, 19, 20, 21]
Upvotes: 11
Reputation: 1653
just append to list till range.
def answer(start,length):
anslist=[start]
for ans in range(length):
anslist.append(start+ans)
print anslist
Upvotes: 1
Reputation: 331
def answer(start, length):
id_arr = list(range(start, start+length))
print(id_arr)
answer(17, 5)
Upvotes: 1
Reputation: 76
Not really, first argument is lower bound and the second is upper bound in terms of half open interval.
list(range(10,20))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Upvotes: 1