· 

Python: lambda as y=f(x)

Topics:

1. sorted(mydictionary.items(), key=myfunction)

2. lambda x: myexpressionwith_x 

3. y = (lambda expression) (x)        #immediately called 

 

1. First Code

 

I don't understand the following code, especially the lambda function.  Can you explain the code in detail?

 

elements = {'helium': 2, 'hydrogen': 1, 'carbon': 6, 'oxygen': 8, 'Nitrogen': 7}

print(elements)

# Sorting the dictionary by values in ascending order

elements = dict(sorted(elements.items(), key=lambda item: item[1]))

print(elements)

 

Sure! Let's break this down step by step so it's super clear. You're dealing with a dictionary, and you're using a lambda function to sort it by values. Here's the code again:

elements = {'helium': 2, 'hydrogen': 1, 'carbon': 6, 'oxygen': 8, 'Nitrogen': 7}

print(elements)

 

# Sorting the dictionary by values in ascending order

elements = dict(sorted(elements.items(), key=lambda item: item[1]))

print(elements)


Step 1: elements dictionary

 

This is a simple dictionary with element names as keys and atomic numbers as values:

{

  'helium': 2,

  'hydrogen': 1,

  'carbon': 6,

  'oxygen': 8,

  'Nitrogen': 7

}


Step 2: elements.items()

 

This returns a view of dictionary items as (key, value) tuples:

[('helium', 2), ('hydrogen', 1), ('carbon', 6), ('oxygen', 8), ('Nitrogen', 7)]

 

 


Step 3: sorted(..., key=...)

You're sorting the items. The key parameter tells Python what value to sort by.

Now let’s explain:

python
key=lambda item: item[1]
  • lambda item: is an anonymous function that takes a tuple like ('helium', 2)

  • item[1] gets the value from the tuple (e.g., 2)

 

So this tells sorted() to sort the list of (key, value) pairs by the value part (not the key).

Step 4: dict(...)

sorted() returns a list of tuples, but you're turning it back into a dictionary using dict().

 

So the final result is:

{

  'hydrogen': 1,

  'helium': 2,

  'carbon': 6,

  'Nitrogen': 7,

  'oxygen': 8

}

 

Summary of the Lambda Function

python
lambda item: item[1]

This is just a shortcut for defining a small function like:

python
def get_value(item):
return item[1]

But it's more concise when you use lambda for one-liners.

 

Let me know if you’d like to see how to sort by key instead, or in descending order!

 

2. Second Code (error)

 

Why doesn't the following code work?

elements = {'helium': 2, 'hydrogen': 1, 'carbon': 6, 'oxygen': 8, 'Nitrogen': 7}

print(elements)

elements = dict(sorted(elements.items(), key=[2,1,6,8,7])

print(elements)

 

Great question! Let's look at your code and why it doesn’t work:

❌ Problematic code:

python
elements = {'helium': 2, 'hydrogen': 1, 'carbon': 6, 'oxygen': 8, 'Nitrogen': 7}
print(elements)
elements = dict(sorted(elements.items(), key=[2,1,6,8,7]))
print(elements)

🔍 What's wrong?

This part is the issue:

python
key=[2,1,6,8,7]

key=... expects a function, not a list

The key argument in sorted() needs to be a function that tells Python how to sort each item. You're passing a list of numbers instead, which doesn't make sense in this context and causes an error like:

php
TypeError: 'list' object is not callable

✅ Correct version:

If you want to sort by the values (as it seems you're trying to do), you should use a lambda function, like this:

python
elements = {'helium': 2, 'hydrogen': 1, 'carbon': 6, 'oxygen': 8, 'Nitrogen': 7}
print(elements)
elements = dict(sorted(elements.items(), key=lambda item: item[1]))
print(elements)

This tells Python to sort based on item[1] (which is the value of each dictionary pair).


🙋‍♂️ Curious follow-up:

If you were trying to sort according to some custom order (like not purely ascending or descending), let me know — I can show you how to sort using a predefined list of values too.

 

Would you like an example of that?

 

 

3. Third Code (error)

 

How about the following?  Is there any way not to use lambda?

def get_value(item):

return item[1]

elements = {'helium': 2, 'hydrogen': 1, 'carbon': 6, 'oxygen': 8, 'Nitrogen': 7}

print(elements)

elements = dict(sorted(elements.items(), key=get_value())

print(elements)

 

You're super close! 👏 You're just making one small mistake — you're calling the function get_value() by writing key=get_value(), but you actually just need to pass the function itself, not call it.


❌ Incorrect:

python
key=get_value() # This calls the function immediately, which is not what we want.

✅ Correct:

python
key=get_value # No parentheses — you're passing the function itself!

✅ Fixed version of your code:

python
def get_value(item):
return item[1]
elements = {'helium': 2, 'hydrogen': 1, 'carbon': 6, 'oxygen': 8, 'Nitrogen': 7}
print(elements)
# Sorting by values using a regular function instead of lambda
elements = dict(sorted(elements.items(), key=get_value))
print(elements)

🧠 Why it works:

  • sorted() expects a function for key, so it can call it on each item.

  • get_value is a function that takes an item (a key-value pair tuple) and returns the value.

  • sorted(elements.items(), key=get_value) sorts those tuples by their second item (the value).

 

Let me know if you’d like to sort it in reverse or by keys instead!

 

 

4. lamda is a way to define a function y=f(x)

 

My understanding of lambda is that lambda is a way to define a function y=f(x).  I wrote a sample code for this.  Am I right?

f = lambda x: x**2 + 2*x + 1 

x =10

y = f(x)

print(y)

 

Yes! You're exactly right — great job! 🙌

Your understanding and example are both spot on:

python
f = lambda x: x**2 + 2*x + 1
x = 10
y = f(x)
print(y)

This is equivalent to writing:

python
def f(x):
return x**2 + 2*x + 1

So yes — lambda is a way to define a small, anonymous function (one that doesn’t need a name unless you assign it like f = lambda x: ...). It’s perfect for short, one-time-use functions.

Your code defines the function
f(x) = x² + 2x + 1,
then evaluates it at x = 10, which gives:

f(10) = 10² + 2*10 + 1 = 100 + 20 + 1 = 121

✅ Output:

121

 

Let me know if you want more examples with lambda, like for sorting or filtering lists!

 

 

5. Better Code

 

If I want to make the code more understandable with y=f(x), I can rewrite the code as follows, right?

elements = {'helium': 2, 'hydrogen': 1, 'carbon': 6, 'oxygen': 8, 'Nitrogen': 7}

print(elements)

# Sorting the dictionary by values in ascending order

elements = dict(sorted(elements.items(), key=lambda x: x[1]))   # y = f(x), f returns the 2nd element of x

print(elements)

 

Yes, absolutely! You're making a great connection — and your comment # y = f(x), f returns the 2nd element of x is exactly what’s happening in the line:

python
elements = dict(sorted(elements.items(), key=lambda x: x[1]))

Let’s break that down with your idea of y = f(x):

  • Here, x is each tuple from elements.items(), like ('helium', 2)

  • x[1] is the value from that tuple (e.g. 2)

  • lambda x: x[1] acts like the function f(x) = x[1]

  • The sorted() function uses that value (x[1]) to sort the items

So this line:

python
elements = dict(sorted(elements.items(), key=lambda x: x[1]))

is just like saying:

python
def f(x):
return x[1]
elements = dict(sorted(elements.items(), key=f))

✅ Both versions are valid, and the lambda form is just a more compact version.

 

Your use of y = f(x) thinking is a great way to understand lambda, especially in sorting or filtering contexts. Want to try the reverse (descending order) or sort by keys instead of values?

 

6. sorting by values in descending order and sorting by keys (alphabetically)

 

Yes. Give me both versions.

 

Awesome! Let’s look at sorting by values in descending order and sorting by keys (alphabetically) — both using:

  1. A lambda function

  2. A regular def function


✅ Sort by values in descending order

1. Using lambda:

python
elements = {'helium': 2, 'hydrogen': 1, 'carbon': 6, 'oxygen': 8, 'Nitrogen': 7}
# Sort by value (descending)
elements = dict(sorted(elements.items(), key=lambda x: x[1], reverse=True))
print(elements)

2. Using def:

python
def get_value(item):
return item[1]
elements = {'helium': 2, 'hydrogen': 1, 'carbon': 6, 'oxygen': 8, 'Nitrogen': 7}
# Sort by value (descending)
elements = dict(sorted(elements.items(), key=get_value, reverse=True))
print(elements)

✅ Sort by keys alphabetically (case-sensitive)

1. Using lambda:

python
elements = {'helium': 2, 'hydrogen': 1, 'carbon': 6, 'oxygen': 8, 'Nitrogen': 7}
# Sort by key
elements = dict(sorted(elements.items(), key=lambda x: x[0]))
print(elements)

2. Using def:

python
def get_key(item):
return item[0]
elements = {'helium': 2, 'hydrogen': 1, 'carbon': 6, 'oxygen': 8, 'Nitrogen': 7}
# Sort by key
elements = dict(sorted(elements.items(), key=get_key))
print(elements)

 

Let me know if you want to ignore case (like 'Nitrogen' being treated the same as 'oxygen') — that’s also possible!

 

 

7. sort by keys alphabetically while ignoring case

 

Yes.  Please give me a version that ignores case.

 

Sure! If you want to sort by keys alphabetically while ignoring case, you can convert each key to lowercase (str.lower) during the sort. Here's how you do it:


✅ Sort by keys alphabetically, ignoring case

1. Using lambda:

python
elements = {'helium': 2, 'hydrogen': 1, 'carbon': 6, 'oxygen': 8, 'Nitrogen': 7}
# Sort by key (ignoring case)
elements = dict(sorted(elements.items(), key=lambda x: x[0].lower()))
print(elements)

2. Using def:

python
def get_key_ignore_case(item):
return item[0].lower()
elements = {'helium': 2, 'hydrogen': 1, 'carbon': 6, 'oxygen': 8, 'Nitrogen': 7}
# Sort by key (ignoring case)
elements = dict(sorted(elements.items(), key=get_key_ignore_case))
print(elements)

🧠 Explanation:

  • x[0] is the key of the (key, value) tuple.

  • .lower() ensures all comparisons treat keys as lowercase, so 'Nitrogen' and 'carbon' sort based on 'nitrogen' and 'carbon'.

 

Let me know if you want to also sort by values while ignoring case or any other variant!

 

 

8. Calling a lambda function immediately

 

Why doesn't the following code work?

#f = lambda x: x**2 + 2*x + 1  

x =10

#y = f(x)

y = lambda x: x**2 + 2*x + 1 (x)

print(y)

 

Great question! The issue in your code is how you're trying to call a lambda function immediately. Let's look at what you're doing and fix it step by step.


❌ Your code:

python
y = lambda x: x**2 + 2*x + 1 (x)

This line is interpreted by Python as:

python
y = (lambda x: x**2 + 2*x + 1)(x)

but you added (x) outside the lambda body, which makes Python confused — especially because you also assign the result to y.


✅ Correct version:

Option 1: Define the lambda first, then call it:

python
f = lambda x: x**2 + 2*x + 1
x = 10
y = f(x)
print(y) # Output: 121

Option 2: Call it immediately without assigning to y first:

python
x = 10
y = (lambda x: x**2 + 2*x + 1)(x)
print(y) # Output: 121

In this version, you're defining the lambda and calling it immediately.


✅ Bonus: Named function version (for readability)

python
def f(x):
return x**2 + 2*x + 1
x = 10
y = f(x)
print(y) # Output: 121

 

Let me know if you’d like to explore anonymous functions more!