To talk a little about Functional programming which these lay under.
So Python has functional features(map,lambda,filter,itertools stuff),but Python is not a functional programming language.
So often there can be discussion what can be most Pytoinc and most effective,there can functional approach not the most popular in Python.
To use example as in Thread as example.
In these simple example both sole the task,so both way here are okay,but one may be preferred if look deeper at it.
If you look at this Thread so did a trow out a
but as you see in next post so did @micseydel think more about it and come up with a better solution.
If want to read more about this look at:
Functional Programming HOWTO
Functional Programming in Python
So Python has functional features(map,lambda,filter,itertools stuff),but Python is not a functional programming language.
So often there can be discussion what can be most Pytoinc and most effective,there can functional approach not the most popular in Python.
To use example as in Thread as example.
def addition(n): ''' Return double of n ''' return n + n # We double all numbers using map() numbers = (1, 2, 3, 4) result = map(addition, numbers) print(list(result)) # Using list comprehension result = [addition(i) for i in numbers] print(result)
Output:[2, 4, 6, 8]
[2, 4, 6, 8]
# Square all numbers using map() and lambda numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 20) result = map(lambda x: x * x, numbers) print(list(result)) # Using list comprehension result = [x * x for x in numbers] print(result)
Output:[1, 4, 9, 16, 25, 36, 49, 64, 81, 400]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 400]
So in many cases can using list comprehension can be look at a better way to solve this in Python.In these simple example both sole the task,so both way here are okay,but one may be preferred if look deeper at it.
If you look at this Thread so did a trow out a
map
example,but as you see in next post so did @micseydel think more about it and come up with a better solution.
If want to read more about this look at:
Functional Programming HOWTO
Functional Programming in Python