7. Lambda Functions

2024. 3. 14. 01:16·Python
6python-lambda-functions

Lambda Functions¶

Lambda functions are "disposable" nameless functions. They are often used as arguments in other functions. For example:

In [1]:
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key = lambda p : p[1])
print(pairs)
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

See its visualization here.

The expression "lambda p : p[1]" defines a nameless function equivalent to the following (see its visualization here):

In [2]:
def getkey(p):
    return p[1]
In [3]:
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key = getkey)
print(pairs)
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

The following is another example where we use a lambda function to extract from a list with the filter command:

In [4]:
squares = [x ** 2 for x in range(100)]
sq = list(filter(lambda x : x % 2 == 0 and x % 3 == 0, squares))
sq
Out[4]:
[0,
 36,
 144,
 324,
 576,
 900,
 1296,
 1764,
 2304,
 2916,
 3600,
 4356,
 5184,
 6084,
 7056,
 8100,
 9216]

It is equivalent to the following:

In [5]:
def multiple_of_6(x):
    return x % 2 == 0 and x % 3 == 0

squares = [x ** 2 for x in range(100)]
sq = list(filter(multiple_of_6, squares))
sq
Out[5]:
[0,
 36,
 144,
 324,
 576,
 900,
 1296,
 1764,
 2304,
 2916,
 3600,
 4356,
 5184,
 6084,
 7056,
 8100,
 9216]

'Python' 카테고리의 다른 글

9. Regular Expression  (0) 2024.03.14
8. Text File I/O  (0) 2024.03.14
6. Recursion vs. Iteration  (1) 2024.03.14
5. Function  (0) 2024.03.14
4. Conditionals and Loops  (0) 2024.03.14
'Python' 카테고리의 다른 글
  • 9. Regular Expression
  • 8. Text File I/O
  • 6. Recursion vs. Iteration
  • 5. Function
Juson
Juson
  • Juson
    Juson의 데이터 공부
    Juson
  • 전체
    오늘
    어제
    • 분류 전체보기 (95)
      • RAG (2)
      • AI (2)
        • NLP (0)
        • Generative Model (0)
        • Deep Reinforcement Learning (2)
        • LLM (0)
      • Logistic Optimization (0)
      • Machine Learning (37)
        • Linear Regression (2)
        • Logistic Regression (2)
        • Decision Tree (5)
        • Naive Bayes (1)
        • KNN (2)
        • SVM (2)
        • Clustering (4)
        • Dimension Reduction (3)
        • Boosting (6)
        • Abnomaly Detection (2)
        • Recommendation (4)
        • Embedding & NLP (4)
      • Reinforcement Learning (5)
      • Deep Learning (10)
        • Deep learning Bacis Mathema.. (10)
      • Optimization (2)
        • OR Optimization (0)
        • Convex Optimization (0)
        • Integer Optimization (0)
      • SNA 분석 (0)
      • 포트폴리오 최적화 공부 (0)
        • 최적화 기법 (0)
        • 금융 베이스 (0)
      • Finanancial engineering (0)
      • 프로그래머스 데브코스(Boot camp) (15)
        • SQL (9)
        • Python (5)
        • Machine Learning (1)
      • Python (22)
      • Project (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
Juson
7. Lambda Functions
상단으로

티스토리툴바