You should be aware of the built-in map , which takes a function as the first argument and is iterable as the second and returns a list of the elements the function acts on. For instance,
>>> def sqr(x): ... return x*x ... >>> map(sqr,range(1,10)) [1, 4, 9, 16, 25, 36, 49, 64, 81] >>>
There is a better way to write the sqr function above, namely using an unnamed lambda with fancy syntax. (Beginners get confused looking for stmt return)
>>> map(lambda x: x*x,range(1,10)) [1, 4, 9, 16, 25, 36, 49, 64, 81]
In addition, you can also use list comprehension.
result = [x*x for x in range(1,10)]
source share