Create a list of integers from from a (inclusive) to b (inclusive).
Example:
integers(2,5) returns [2, 3, 4, 5].
I know this is probably an easy one, but I just can't seem to get anything to work.
A list comprehension makes the most sense here. It's terse and doesn't involve appending unnecessarily to the list (on your end).
def integers(a, b):
return [i for i in range(a, b+1)]
>>> def integers(a, b):
return list(range(a, b+1))
>>> integers(2, 5)
[2, 3, 4, 5]
To explain your own solution:
can you explain to me why in some programs you have to include
[i]and some it is justidef integers(a,b): list = [] for i in range(a, b+1): list = list + [i]
i refers to the number itself; [i] is a list with one element, i. When using the + operator for lists, Python can concat two lists, so [1, 2] + [3, 4] is [1, 2, 3, 4]. It is however not possible to just add a single element (or number in this case) to an existing list. Trying so will result in a TypeError.
What you could do instead of concatenating with a one-element list, is simply append the element by using the method with the same name:
list.append(i)
One final note, you should not name your variable list (or dict or str etc) as that will locally overwrite the references to the built-in functions/types.
use np.arange. Example
i=np.arange(1,9)
This will result in
array([ 1, 2, 3, 4, 5, 6, 7, 8])
Arrays are nicer than lists in python
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