Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Create a List Starting at a Given Value and End at Given Length

Tags:

python

list

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?

like image 670
Gabriel_W Avatar asked Mar 21 '17 06:03

Gabriel_W


People also ask

How do you initiate a list with a specific length in Python?

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.

How do I make a list start and end?

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.

How do I create a fixed size list in Python?

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).

Can Len () be used for lists Python?

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.


2 Answers

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]
like image 117
Shivkumar kondi Avatar answered Sep 24 '22 19:09

Shivkumar kondi


in your def

id_arr = list(range(start, start+length))

should give you the desired result

like image 42
VarunT Avatar answered Sep 26 '22 19:09

VarunT