Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a list of integers from a to b in python

Tags:

python-3.x

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.

like image 597
knd15 Avatar asked Dec 12 '12 22:12

knd15


3 Answers

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)]
like image 40
Makoto Avatar answered Nov 05 '22 05:11

Makoto


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

like image 75
poke Avatar answered Nov 05 '22 06:11

poke


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

like image 2
Jimmy TwoCents Avatar answered Nov 05 '22 04:11

Jimmy TwoCents