create a list of integers from a to b in python

python-3.x

Solution

>>> 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 just `i`

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

Problem

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.

Original source