In the earlier article, we have seen the use of global, and the different flavors of functions in Python.
Let''s combine them and use comprehensions to reduce the total lines of code.
What are comprehensions in Python?
In Python, comprehensions are a concise and expressive way to create new sequences—like lists, sets, dictionaries, or generators—from existing iterables. They let you write elegant one-liners that would otherwise require multiple lines of loops and conditionals.
Comprehensions work like the Arabic language, read from right-to-left
🔍 Observations
- In the above screenshot, in
modify(old_emp, new_emp)
, the execution happens in a sequential top-to-down manner. - In
modify_smart(old,new)
, the same execution happens in one-line from right to left
Let's highlight the comprehension in the modify_smart()
🔍 Investigating the above code:
for emp in company_employees
: Iterate over each employee name in the list.new if emp == old else emp
: If the employee name matchesold
, replace it withnew
; otherwise, keep it unchanged.
No comments:
Post a Comment