Lambda Fungsi
- Ing Python, a
lambda
minangka fungsi anonim sing digawe nggunakakelambda
tembung kunci. - Lambda fungsi kasusun saka siji, expression prasaja lan asring digunakake nalika sampeyan perlu fungsi ringkes tanpa nemtokake fungsi kapisah.
- Sintaks sawijining lambda fungsi yaiku:
lambda arguments: expression
Tuladha:
# Lambda function to calculate square
square = lambda x: x**2
print(square(5)) # Output: 25
# Lambda function to calculate the sum of two numbers
add = lambda a, b: a + b
print(add(3, 7)) # Output: 10
Functional Programming
- Functional Programming minangka gaya pemrograman adhedhasar nggunakake fungsi lan ngindhari variabel stateful.
- Ing Python, sampeyan bisa ngleksanakake Functional Programming nggunakake cara kaya
map()
,filter()
,reduce()
, lan lambda fungsi. - Fungsi kasebut ngidini sampeyan nindakake operasi ing data tanpa ngganti statuse.
Tuladha:
# Using map() and lambda function to calculate squares of numbers in a list
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
# Using filter() and lambda function to filter even numbers in a list
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4]
Functional Programming ing Python ndadekake kode luwih bisa diwaca, maintainable, lan extensible. Iki uga mbantu sampeyan ngindhari masalah sing ana gandhengane karo variabel stateful lan minangka gaya program populer ing pangembangan piranti lunak.