I assume you have NumPy installed (at least your original question suggested it), so I'll present a way how you can get your result using numpy-arrays
in a very efficient manner (without any list-comprehensions and explicit iterations):
> import numpy as np
> s = 10
> l = np.arange(1, 100) * 2 + s * 2 # Arrange produces an array. Syntax is like "range".
> print(l)
array([ 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46,
48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72,
74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98,
100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124,
126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150,
152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176,
178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200, 202,
204, 206, 208, 210, 212, 214, 216, 218])
I used the fact that mathematical operations on NumPy arrays affect all elements. Therefore it is so easy to write the operation: np.arange(1, 100) * 2
, because it multiplies every element with 2
and numpy.arange
is a possibility to create an array containing all the numbers between a given start
and stop
with an optional step
(just like the python range
).
With NumPy it wouldn't be a good choice to append
single values (because this recreates the whole array and not just appends values). In most cases it's best to create an array with the final size and shape and operate directly on it. Of course you can concatenate
or append
different NumPy arrays, but as mentioned it always creates a completely new array and is therefore not very efficient (if used regularly).
So now a few observations on your initial attempt and why it didn't work: Your function created lots of numbers, but it overrides them in each loop and only returns the last one:
def func(s):
for i in range(1, 100):
t = i
p = t * 2 + s * 2
# Next iteration of the loop just overwrites p
# Returns only the last p
return p
You could make this a generator (with yield
instead of return
), but that's probably overkill here, I'll show it nevertheless :-)
l = []
def func(s):
for i in range(1, 100):
p = i * 2 + s * 2
yield p
l.append(list(func(10))) # Need to convert the generator to a list here.
# In this case a simple "l = list(func(10))" would be easier if you don't need to append.