Python 2.7.10
What you described is mapping; it does involve loops in the background, but it achieves your succinctness. Here's an example.
l = [1,2,3]
#f returns n^2
def f(n):
return n*n
l = map(f, l) #[1,4,9]
map
applies the function f
to every element of l
.
map
also works on sets; however, map returns back a list of values e.g. f({x1,x2,x3}) = [f(x1),f(x2),f(x3)]
, in an arbitrary order. You can turn the returned list back into a set by wrapping it as a set
.
Python 3.6
In Python 3.6, map
returns back a map object, and you will need to convert it to your desired typed. This example shows the map object converted to a list.
l = [1,2,3]
def f(n):
return n*n
l = list(map(f, l)) #[1,4,9]
Alternatively, you can reduce the amount of code further using lambda functions, making it more succinct.
l = [1,2,3]
l = map(lambda x:x*x, l)
Where the lambda expression has the functionality f
but used only there and non-existent afterwards.