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?
You can initialize a list of a custom size using either multiplication or a range() statement. The multiplication method is best if you want to initialize a list with the same values. A range() statement is a good choice if you want a list to contain values in a particular range.
To create a list from another list with given start and end indexes, use list[n1:n2] notation, in the program, the indexes are start and end. Thus, the statement to create list is list1 = list[start: end+1]. Finally, print the lists.
You can use this: [None] * 10 . But this won't be "fixed size" you can still append, remove ... This is how lists are made. You could make it a tuple ( tuple([None] * 10) ) to fix its width, but again, you won't be able to change it (not in all cases, only if the items stored are mutable).
The function len() is one of Python's built-in functions. It returns the length of an object. For example, it can return the number of items in a list. You can use the function with many different data types.
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]
in your def
id_arr = list(range(start, start+length))
should give you the desired result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With